139 lines
6.5 KiB
PHP
139 lines
6.5 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
namespace app\service;
|
|
|
|
use app\exception\ApiError;
|
|
use app\repository\IdentityRepository;
|
|
|
|
final class AuthService
|
|
{
|
|
public function __construct(private readonly IdentityRepository $repository)
|
|
{
|
|
}
|
|
|
|
public function login(array $data, string $ip): array
|
|
{
|
|
Input::only($data, ['account', 'password']);
|
|
$account = Input::account($data['account'] ?? null);
|
|
$password = $data['password'] ?? null;
|
|
if (!is_string($password) || strlen($password) > 72 || str_contains($password, "\0")) {
|
|
throw new ApiError(422, '密码格式错误');
|
|
}
|
|
$limiter = new LoginLimiter();
|
|
$limiter->reserve($ip, $account);
|
|
$admin = $this->repository->db->one('SELECT * FROM admin WHERE account = ?', [$account]);
|
|
// The dummy hash equalizes expensive verification for nonexistent accounts.
|
|
$hash = $admin['password_hash'] ?? '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
|
|
$verified = password_verify($password, $hash);
|
|
if (!$admin || !$verified || (int) $admin['disable'] !== 0) {
|
|
throw new ApiError(401, '账号或密码错误,或账号已停用');
|
|
}
|
|
$limiter->success($ip, $account);
|
|
$token = bin2hex(random_bytes(32));
|
|
$ttl = max(300, min(604800, (int) Settings::get('IAM_SESSION_TTL', '28800')));
|
|
$this->repository->db->transaction(function () use ($admin, $token, $ttl): void {
|
|
// Recheck under a transaction so a disabled account cannot mint an accepted session.
|
|
$current = $this->repository->require('admin', (int) $admin['id']);
|
|
if ((int) $current['disable'] !== 0 || !hash_equals($current['password_hash'], $admin['password_hash'])) {
|
|
throw new ApiError(401, '账号状态已变化,请重新登录');
|
|
}
|
|
$this->repository->db->execute('DELETE FROM admin_session WHERE expire_time <= ?', [time()]);
|
|
$this->repository->insert('admin_session', ['admin_id' => $admin['id'], 'token_hash' => hash('sha256', $token),
|
|
'expire_time' => time() + $ttl, 'create_time' => time()]);
|
|
});
|
|
return ['token' => $token];
|
|
}
|
|
|
|
public function authenticate(string $authorization): array
|
|
{
|
|
if (!preg_match('/^Bearer ([a-f0-9]{64})$/D', $authorization, $matches)) {
|
|
throw new ApiError(401, '请先登录');
|
|
}
|
|
$hash = hash('sha256', $matches[1]);
|
|
$admin = $this->repository->db->one('SELECT a.* FROM admin a JOIN admin_session s ON s.admin_id=a.id WHERE s.token_hash=? AND s.expire_time>? AND a.disable=0', [$hash, time()]);
|
|
if (!$admin) {
|
|
throw new ApiError(401, '登录已失效,请重新登录');
|
|
}
|
|
return ['admin' => $admin, 'token_hash' => $hash];
|
|
}
|
|
|
|
public function permissions(array $admin): array
|
|
{
|
|
if ((int) $admin['is_root'] === 1) {
|
|
return ['*'];
|
|
}
|
|
$grants = $this->repository->db->all('SELECT DISTINCT rm.menu_id FROM system_role_menu rm JOIN system_role r ON r.id=rm.role_id JOIN admin_role ar ON ar.role_id=r.id WHERE ar.admin_id=? AND r.disable=0', [$admin['id']]);
|
|
$ids = array_fill_keys(array_map('intval', array_column($grants, 'menu_id')), true);
|
|
$permissions = [];
|
|
foreach (TreeService::effective($this->repository->db->all('SELECT * FROM system_menu')) as $menu) {
|
|
if (isset($ids[(int) $menu['id']]) && $menu['perms'] !== '') {
|
|
$permissions[] = $menu['perms'];
|
|
}
|
|
}
|
|
return array_values(array_unique($permissions));
|
|
}
|
|
|
|
public function menus(array $admin, array $permissions): array
|
|
{
|
|
$rows = TreeService::effective($this->repository->db->all('SELECT * FROM system_menu ORDER BY sort DESC,id ASC'));
|
|
$byId = array_column($rows, null, 'id');
|
|
$allowed = [];
|
|
foreach ($rows as $row) {
|
|
if ($row['type'] === 'A') {
|
|
continue;
|
|
}
|
|
if ((int) $admin['is_root'] !== 1 && $row['paths'] !== '/dashboard' && !in_array($row['perms'], $permissions, true)) {
|
|
continue;
|
|
}
|
|
$id = (int) $row['id'];
|
|
while ($id > 0 && isset($byId[$id]) && !isset($allowed[$id])) {
|
|
$allowed[$id] = true;
|
|
$id = (int) $byId[$id]['pid'];
|
|
}
|
|
}
|
|
return TreeService::build(array_values(array_filter($rows, static fn ($row) => isset($allowed[(int) $row['id']]) && $row['type'] !== 'A')));
|
|
}
|
|
|
|
public function myself(array $admin): array
|
|
{
|
|
$user = $this->repository->publicAdmin($admin);
|
|
$user['permissions'] = $this->permissions($admin);
|
|
$user['menus'] = $this->menus($admin, $user['permissions']);
|
|
return $user;
|
|
}
|
|
|
|
public function logout(string $hash): array
|
|
{
|
|
$this->repository->db->execute('DELETE FROM admin_session WHERE token_hash=?', [$hash]);
|
|
return [];
|
|
}
|
|
|
|
public function password(array $admin, array $data, string $tokenHash): array
|
|
{
|
|
Input::only($data, ['old_password', 'password', 'password_confirm']);
|
|
if (!is_string($data['old_password'] ?? null) || strlen($data['old_password']) > 72) {
|
|
throw new ApiError(422, '原密码错误');
|
|
}
|
|
$password = Input::password($data['password'] ?? null);
|
|
if ($password !== ($data['password_confirm'] ?? null)) {
|
|
throw new ApiError(422, '两次密码不一致');
|
|
}
|
|
$this->repository->db->transaction(function () use ($admin, $data, $password, $tokenHash): void {
|
|
// Re-read both identity and session after acquiring the write transaction. Never trust the authentication snapshot for a password change.
|
|
$current = $this->repository->db->one(
|
|
'SELECT a.* FROM admin a JOIN admin_session s ON s.admin_id=a.id WHERE a.id=? AND s.token_hash=? AND s.expire_time>? AND a.disable=0',
|
|
[(int) $admin['id'], $tokenHash, time()]
|
|
);
|
|
if (!$current) {
|
|
throw new ApiError(401, '登录已失效,请重新登录');
|
|
}
|
|
if (!password_verify($data['old_password'], $current['password_hash'])) {
|
|
throw new ApiError(422, '原密码错误');
|
|
}
|
|
$this->repository->update('admin', (int) $current['id'], ['password_hash' => password_hash($password, PASSWORD_DEFAULT)]);
|
|
$this->repository->db->execute('DELETE FROM admin_session WHERE admin_id=?', [$current['id']]);
|
|
});
|
|
return [];
|
|
}
|
|
}
|