This commit is contained in:
gr
2026-11-11 14:22:02 +08:00
parent 245618dcdc
commit a62311a8da
64878 changed files with 3747172 additions and 66 deletions
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\common\cache\AdminAuthCache;
use app\common\cache\AdminTokenCache;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminRole;
use app\common\model\auth\AdminSession;
use app\common\model\auth\SystemMenu;
use app\common\model\auth\SystemRoleMenu;
use think\facade\Log;
/** 原账号变更:事务内锁账号并撤销会话,提交成功后才清缓存。 */
final class AdminAccessSyncService
{
public static function ids(array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn (int $id): bool => $id > 0)));
sort($ids, SORT_NUMERIC);
return $ids;
}
public static function roleAdminIds(array $roleIds): array
{
return $roleIds === [] ? [] : self::ids(AdminRole::whereIn('role_id', $roleIds)->column('admin_id'));
}
/** 菜单父节点变更也影响只获授子节点的账号。 */
public static function menuAdminIds(int $menuId): array
{
$menuIds = [$menuId];
$rows = SystemMenu::field('id,pid')->select()->toArray();
do {
$count = count($menuIds);
foreach ($rows as $row) {
if (in_array((int) $row['pid'], $menuIds, true)) { $menuIds[] = (int) $row['id']; }
}
$menuIds = self::ids($menuIds);
} while (count($menuIds) !== $count);
return self::roleAdminIds(self::ids(SystemRoleMenu::whereIn('menu_id', $menuIds)->column('role_id')));
}
/** 调用者必须已开启事务;与密码登录、SSO签发和续期共用账号锁。 */
public static function revoke(array $adminIds): array
{
$adminIds = self::ids($adminIds);
if ($adminIds === []) { return []; }
Admin::whereIn('id', $adminIds)->order('id')->lock(true)->field('id')->select();
$tokens = AdminSession::whereIn('admin_id', $adminIds)->column('token');
AdminSession::whereIn('admin_id', $adminIds)->update(['expire_time' => time() - 1, 'update_time' => time()]);
return $tokens;
}
public static function clearCommitted(array $adminIds, array $tokens): void
{
// DB是有效性的准绳;缓存故障不能把已提交操作伪报失败,也不能恢复旧会话。
foreach ($tokens as $token) {
try { (new AdminTokenCache())->deleteAdminInfo((string) $token); }
catch (\Throwable $error) { Log::warning('账号变更已提交,会话缓存清理失败'); }
}
foreach (self::ids($adminIds) as $adminId) {
try { (new AdminAuthCache($adminId))->clearAuthCache(); }
catch (\Throwable $error) { Log::warning('账号变更已提交,权限缓存清理失败:admin_id=' . $adminId); }
}
}
}
@@ -0,0 +1,143 @@
<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\service;
use app\common\cache\AdminTokenCache;
use app\common\model\auth\AdminSession;
use app\common\model\auth\Admin;
use think\facade\Config;
use think\facade\Db;
/**
* 管理员token
* Class AdminTokenService
* @package app\adminapi\service
*/
class AdminTokenService
{
/**
* @notes 设置或更新管理员token
* @param $adminId //管理员id
* @param $terminal //多终端名称
* @param $multipointLogin //是否支持多处登录
* @return false|mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/2 20:25
*/
public static function setToken($adminId, $terminal, $multipointLogin = 1)
{
return Db::transaction(static function () use ($adminId, $terminal, $multipointLogin) {
$admin = Admin::where('id', $adminId)->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) { return false; }
$time = time();
$adminSession = AdminSession::where([['admin_id', '=', $adminId], ['terminal', '=', $terminal]])->find();
//获取token延长过期的时间
$expireTime = $time + Config::get('project.admin_token.expire_duration');
$adminTokenCache = new AdminTokenCache();
//token处理
if ($adminSession) {
if ($adminSession->expire_time < $time || $multipointLogin === 0) {
//清空缓存
$adminTokenCache->deleteAdminInfo($adminSession->token);
//如果token过期或账号设置不支持多处登录,更新token
$adminSession->token = create_token($adminId);
}
$adminSession->expire_time = $expireTime;
$adminSession->update_time = $time;
$adminSession->save();
} else {
//找不到在该终端的token记录,创建token记录
$adminSession = AdminSession::create([
'admin_id' => $adminId,
'terminal' => $terminal,
'token' => create_token($adminId),
'expire_time' => $expireTime
]);
}
return $adminTokenCache->setAdminInfo($adminSession->token);
});
}
/**
* @notes 延长token过期时间
* @param $token
* @return array|false|mixed
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/5 14:25
*/
public static function overtimeToken($token)
{
return Db::transaction(static function () use ($token) {
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { return false; }
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) { return false; }
$time = time();
$adminSession = AdminSession::where('token', '=', $token)->where('expire_time', '>', $time)->lock(true)->findOrEmpty();
if ($adminSession->isEmpty()) {
return false;
}
//延长token过期时间
$adminSession->expire_time = $time + Config::get('project.admin_token.expire_duration');
$adminSession->update_time = $time;
$adminSession->save();
$cache = new AdminTokenCache();
$cached = $cache->get('token_admin_' . $token);
if ($cached) {
// 续期不得把登录IP改绑到当前请求IP。
$cached['expire_time'] = $adminSession->expire_time;
$cache->set('token_admin_' . $token, $cached, new \DateTime(date('Y-m-d H:i:s', $adminSession->expire_time)));
return $cached;
}
return $cache->setAdminInfo($adminSession->token);
});
}
/**
* @notes 设置token为过期
* @param $token
* @return bool
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
* @author 令狐冲
* @date 2021/7/5 14:31
*/
public static function expireToken($token)
{
$changed = Db::transaction(static function () use ($token): bool {
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) { return false; }
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
// 保留原退出登录在多点登录模式下不注销的语义。
if (!$admin->isEmpty() && (int) $admin['multipoint_login'] === 1) { return false; }
return AdminSession::where('token', $token)->update(['expire_time' => time() - 1, 'update_time' => time()]) > 0;
});
if ($changed) { (new AdminTokenCache())->deleteAdminInfo($token); }
return $changed;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
/** 核心账号管理接口独立于可编辑菜单的URI登记,删除菜单也不能变成免鉴权接口。 */
final class CoreAccountPermissionPolicy
{
/** null=非核心接口;[]为已登录账号自己的资料或导航接口;其余为允许的原权限别名。 */
public static function aliases(string $uri): ?array
{
[$controller, $action] = array_pad(explode('/', strtolower($uri), 2), 2, '');
if (!in_array($controller, ['auth.admin', 'auth.role', 'auth.menu', 'dept.dept'], true)) { return null; }
if (($controller === 'auth.admin' && in_array($action, ['myself', 'editself', 'bindworkwechat', 'unbindworkwechat'], true))
|| ($controller === 'auth.menu' && $action === 'route')) { return []; }
$aliases = [$uri];
if ($action === 'detail') { $aliases = array_merge($aliases, [$controller . '/lists', $controller . '/edit']); }
if ($action === 'all' || ($controller === 'dept.dept' && $action === 'leaderdept')) {
$aliases = array_merge($aliases, [$controller . '/lists', $controller . '/add', $controller . '/edit']);
if (in_array($controller, ['auth.role', 'dept.dept'], true)) {
$aliases = array_merge($aliases, ['auth.admin/add', 'auth.admin/edit']);
}
if ($controller === 'auth.menu') { $aliases = array_merge($aliases, ['auth.role/add', 'auth.role/edit']); }
}
if ($controller === 'auth.menu' && $action === 'updatestatus') { $aliases[] = 'auth.menu/edit'; }
return $aliases;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\adminapi\logic\LoginLogic;
use app\adminapi\http\middleware\AuthMiddleware;
use app\common\cache\AdminTokenCache;
use app\common\enum\AdminTerminalEnum;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminSession;
use app\common\service\JsonService;
use think\facade\Config;
use think\facade\Db;
/** The hospital trusts its own live source session, never a caller-provided identity. */
final class IdentityHospitalSsoService
{
private IdentityHospitalSsoTicketStore $tickets;
public function __construct(?IdentityHospitalSsoTicketStore $tickets = null)
{
$this->tickets = $tickets ?? new IdentityHospitalSsoTicketStore(app()->getRuntimePath() . 'identity-hospital-sso');
}
public function issue(string $sourceToken, array $data): array
{
self::only($data, ['code_challenge', 'code_challenge_method']);
if (($data['code_challenge_method'] ?? null) !== 'S256'
|| !is_string($data['code_challenge'] ?? null)
|| !preg_match('/^[A-Za-z0-9_-]{43}$/D', $data['code_challenge'])) {
JsonService::throw('登录验证参数不合法');
}
if ($sourceToken === '' || strlen($sourceToken) > 512 || preg_match('/[\x00-\x20\x7f]/', $sourceToken)) {
JsonService::throw('请先登录集团工作台', [], -1);
}
return Db::transaction(function () use ($sourceToken, $data): array {
$candidate = AdminSession::where('token', $sourceToken)->findOrEmpty();
[$admin, $session] = self::lockSource($candidate, hash('sha256', $sourceToken));
self::ready($admin);
// 交接源仍受原 IP 绑定保护;目标 exchange 才允许来自医院浏览器的不同 IP。
$info = (new AdminTokenCache())->getAdminInfo($sourceToken);
$ip = request()->ip();
if (!$info || (int) ($info['admin_id'] ?? 0) !== (int) $admin['id']
|| (($info['login_ip'] ?? '') !== $ip && !AuthMiddleware::isTrustedRpaServerRequest(
(array) $info, $ip, env('wecom_rpa.server_ips', '')))) {
JsonService::throw('ip地址发生变化,请重新登录', [], -1);
}
return ['ticket' => $this->tickets->issue((int) $session['id'], hash('sha256', $sourceToken), $data['code_challenge'])];
});
}
public function exchange(array $data): array
{
self::only($data, ['ticket', 'code_verifier']);
if (!is_string($data['ticket'] ?? null) || !is_string($data['code_verifier'] ?? null)) {
JsonService::throw('登录验证参数不合法');
}
try { $record = $this->tickets->consume($data['ticket'], $data['code_verifier']); }
catch (\RuntimeException $error) { JsonService::throw('登录票据已失效,请重新从集团工作台进入'); }
$result = Db::transaction(static function () use ($record): array {
$candidate = AdminSession::where('id', $record['session_id'])->findOrEmpty();
[$admin] = self::lockSource($candidate, $record['token_hash']);
self::ready($admin);
$now = time();
$target = AdminSession::where('admin_id', (int) $admin['id'])
->where('terminal', AdminTerminalEnum::GROUP_HOSPITAL)->lock(true)->findOrEmpty();
$oldToken = $target->isEmpty() ? '' : (string) $target['token'];
$token = $oldToken;
if ($target->isEmpty() || (int) $target['expire_time'] <= $now || (int) $admin['multipoint_login'] === 0) {
// 原 admin_session.token 为 varchar(32),保持128位随机性且不修改业务表。
$token = bin2hex(random_bytes(16));
}
$values = ['token' => $token, 'expire_time' => $now + (int) Config::get('project.admin_token.expire_duration'),
'update_time' => $now];
if ($target->isEmpty()) {
AdminSession::create($values + ['admin_id' => (int) $admin['id'], 'terminal' => AdminTerminalEnum::GROUP_HOSPITAL]);
} else { $target->save($values); }
// Persist the independent session under the same account/source locks. Publish its cache only after commit.
return ['token' => $token, 'old_token' => $oldToken, 'name' => (string) $admin['name'],
'avatar' => (string) $admin['avatar']];
});
$cache = new AdminTokenCache();
if ($result['old_token'] !== '' && $result['old_token'] !== $result['token']) {
$cache->deleteAdminInfo($result['old_token']);
}
// This executes in the real hospital browser request, retaining the original per-token IP protection.
$info = $cache->setAdminInfo($result['token']);
if (!$info) { JsonService::throw('登录已失效,请重新进入', [], -1); }
return ['name' => $result['name'], 'avatar' => $result['avatar'], 'role_name' => $info['role_name'],
'token' => $result['token'], 'is_paw' => 1, 'need_bind_work_wechat' => false];
}
private static function lockSource(AdminSession $candidate, string $tokenHash): array
{
if ($candidate->isEmpty()) { JsonService::throw('集团登录已失效,请重新登录', [], -1); }
// Same order as IdentitySessionService and account changes: account row, then the exact session row.
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0 || !empty($admin->getData('delete_time'))) {
JsonService::throw('集团登录已失效,请重新登录', [], -1);
}
$session = AdminSession::where('id', (int) $candidate['id'])->where('admin_id', (int) $admin['id'])
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
if ($session->isEmpty() || !hash_equals($tokenHash, hash('sha256', (string) $session['token']))
|| (int) $session['terminal'] === AdminTerminalEnum::GROUP_HOSPITAL) {
JsonService::throw('集团登录已失效,请重新登录', [], -1);
}
return [$admin, $session];
}
private static function ready(Admin $admin): void
{
if ((int) $admin['is_paw'] !== 1) { JsonService::throw('请先在集团工作台完成首次密码修改'); }
if (LoginLogic::adminMustBindWorkWechat(['root' => (int) $admin['root'],
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? '')])) {
JsonService::throw('请先在原后台完成企业微信绑定', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
}
}
private static function only(array $data, array $allowed): void
{
if (array_diff(array_keys($data), $allowed) !== []) { JsonService::throw('请求包含不支持的字段'); }
}
}
@@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use RuntimeException;
/** Private single-server handoff tickets. Neither raw source tokens nor passwords are persisted. */
final class IdentityHospitalSsoTicketStore
{
private \Closure $clock;
public function __construct(private string $directory, ?callable $clock = null)
{
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
}
public function issue(int $sessionId, string $tokenHash, string $challenge): string
{
return $this->locked(function () use ($sessionId, $tokenHash, $challenge): string {
foreach (array_slice(glob($this->directory . '/*.json') ?: [], 0, 200) as $path) {
$old = $this->read($path);
if ($old !== null && (int) ($old['expires'] ?? 0) <= ($this->clock)()) { unlink($path); }
}
$ticket = bin2hex(random_bytes(32));
$record = ['session_id' => $sessionId, 'token_hash' => $tokenHash, 'challenge' => $challenge,
'expires' => ($this->clock)() + 30];
$path = $this->path($ticket);
$file = fopen($path, 'x+b');
if ($file === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
try {
chmod($path, 0600);
$json = json_encode($record, JSON_THROW_ON_ERROR);
if (fwrite($file, $json) !== strlen($json) || !fflush($file)) {
throw new RuntimeException('Hospital handoff storage unavailable');
}
} catch (\Throwable $error) {
fclose($file);
unlink($path);
throw $error;
}
fclose($file);
return $ticket;
});
}
public function consume(string $ticket, string $verifier): array
{
if (!preg_match('/^[a-f0-9]{64}$/D', $ticket)
|| !preg_match('/^[A-Za-z0-9._~-]{43,128}$/D', $verifier)) {
throw new RuntimeException('Hospital handoff invalid');
}
return $this->locked(function () use ($ticket, $verifier): array {
$path = $this->path($ticket);
$record = $this->read($path);
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
if ($record === null || !is_int($record['expires'] ?? null) || $record['expires'] <= ($this->clock)()
|| !is_int($record['session_id'] ?? null) || $record['session_id'] < 1
|| !is_string($record['token_hash'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $record['token_hash'])
|| !is_string($record['challenge'] ?? null) || !hash_equals($record['challenge'], $challenge)) {
throw new RuntimeException('Hospital handoff invalid');
}
// The global private lock covers open/read/delete, so simultaneous exchanges cannot replay.
if (!unlink($path)) { throw new RuntimeException('Hospital handoff consumption failed'); }
return $record;
});
}
private function read(string $path): ?array
{
if (!is_file($path) || is_link($path) || filesize($path) > 4096) { return null; }
try { $record = json_decode((string) file_get_contents($path), true, 8, JSON_THROW_ON_ERROR); }
catch (\JsonException $error) { return null; }
return is_array($record) ? $record : null;
}
private function path(string $ticket): string
{
return $this->directory . '/' . hash('sha256', $ticket) . '.json';
}
private function locked(callable $operation): mixed
{
if (is_link($this->directory) || (!is_dir($this->directory)
&& !mkdir($this->directory, 0700, true) && !is_dir($this->directory))) {
throw new RuntimeException('Hospital handoff storage unavailable');
}
chmod($this->directory, 0700);
$path = $this->directory . '/.lock';
if (is_link($path)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
$lock = fopen($path, 'c+b');
if ($lock === false) { throw new RuntimeException('Hospital handoff storage unavailable'); }
chmod($path, 0600);
try {
if (!flock($lock, LOCK_EX)) { throw new RuntimeException('Hospital handoff storage unavailable'); }
return $operation();
} finally { flock($lock, LOCK_UN); fclose($lock); }
}
}
@@ -0,0 +1,158 @@
<?php
declare(strict_types=1);
namespace app\adminapi\service;
use app\adminapi\logic\LoginLogic;
use app\common\cache\AdminTokenCache;
use app\common\model\auth\Admin;
use app\common\model\auth\AdminSession;
use app\common\service\JsonService;
use think\facade\Config;
use think\facade\Db;
/** 共用原账号密码与原会话,不信任桥接层提供的用户编号或root标记。 */
final class IdentitySessionService
{
/** 验证外部子系统的凭据,不创建、复用、刷新或注销原系统会话。 */
public static function verify(array $params): array
{
if (array_diff(array_keys($params), ['account', 'password']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$account = $params['account'] ?? null;
$password = $params['password'] ?? null;
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")) {
JsonService::throw('登录参数不合法');
}
return Db::transaction(static function () use ($account, $password): array {
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
$salt = (string) Config::get('project.unique_identification');
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
}
return ['id' => (int) $admin['id'], 'account' => (string) $admin['account'],
'name' => (string) ($admin['name'] ?? ''), 'disable' => 0,
'requires_password_change' => (int) ($admin['is_paw'] ?? 1) === 0,
'requires_wecom_binding' => LoginLogic::adminMustBindWorkWechat([
'root' => (int) ($admin['root'] ?? 0),
'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
])];
});
}
/** 与个人改密共用账号行锁,绝不信任事务前验证器的密码快照或调试免密结果。 */
public static function login(array $params): array
{
if (array_diff(array_keys($params), ['account', 'password', 'terminal']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$account = $params['account'] ?? null;
$password = $params['password'] ?? null;
$terminal = $params['terminal'] ?? null;
if (!is_string($account) || $account === '' || strlen($account) > 4096 || str_contains($account, "\0")
|| !is_string($password) || $password === '' || strlen($password) > 4096 || str_contains($password, "\0")
|| (!is_int($terminal) && !is_string($terminal)) || !in_array((string) $terminal, ['1', '2', '7', '9'], true)) {
JsonService::throw('登录参数不合法');
}
return Db::transaction(static function () use ($account, $password, $params): array {
$admin = Admin::where('account', $account)->lock(true)->findOrEmpty();
$salt = (string) Config::get('project.unique_identification');
if ($admin->isEmpty() || (int) $admin['disable'] !== 0
|| !hash_equals((string) $admin['password'], create_password($password, $salt))) {
JsonService::throw('账号或密码错误,或账号已停用', [], -1);
}
// 原登录的资料更新和会话签发均在该账号锁释放前完成。
return (new LoginLogic())->login($params);
});
}
public static function changePassword(string $token, array $params): void
{
if (array_diff(array_keys($params), ['old_password', 'password', 'password_confirm']) !== []) {
JsonService::throw('请求包含不支持的字段');
}
$password = $params['password'] ?? null;
if (!is_string($password) || strlen($password) < 6 || strlen($password) > 32 || str_contains($password, "\0")) {
JsonService::throw('密码长度须在6-32字节');
}
if ($password !== ($params['password_confirm'] ?? null)) {
JsonService::throw('两次输入的密码不一致');
}
$tokens = Db::transaction(static function () use ($token, $params, $password): array {
[$admin] = self::lockContext($token);
$firstPassword = (int) ($admin['is_paw'] ?? 1) === 0;
if (!$firstPassword && LoginLogic::adminMustBindWorkWechat([
'root' => (int) $admin['root'], 'work_wechat_userid' => (string) ($admin['work_wechat_userid'] ?? ''),
])) {
JsonService::throw('请先在原后台绑定企业微信', [], LoginLogic::CODE_NEED_BIND_WORK_WECHAT);
}
$salt = (string) Config::get('project.unique_identification');
if (!$firstPassword) {
$oldPassword = $params['old_password'] ?? null;
if (!is_string($oldPassword) || strlen($oldPassword) > 1024
|| !hash_equals((string) $admin['password'], create_password($oldPassword, $salt))) {
JsonService::throw('当前密码错误');
}
}
$id = (int) $admin['id'];
Admin::where('id', $id)->update([
'password' => create_password($password, $salt), 'is_paw' => 1, 'update_time' => time(),
]);
return self::expire($id, null);
});
self::clearTokens($tokens);
}
public static function logout(string $token, bool $all = false): void
{
$tokens = Db::transaction(static function () use ($token, $all): array {
[$admin] = self::lockContext($token);
return self::expire((int) $admin['id'], $all ? null : $token);
});
self::clearTokens($tokens);
}
/** 先锁账号再锁会话,避免两个会话同时改密时互相等待。 */
private static function lockContext(string $token): array
{
if ($token === '' || strlen($token) > 512 || preg_match('/[\x00-\x20\x7f]/', $token)) {
JsonService::throw('请先登录', [], -1);
}
$candidate = AdminSession::where('token', $token)->findOrEmpty();
if ($candidate->isEmpty()) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
$admin = Admin::where('id', (int) $candidate['admin_id'])->lock(true)->findOrEmpty();
if ($admin->isEmpty() || (int) $admin['disable'] !== 0) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
$session = AdminSession::where('admin_id', (int) $admin['id'])->where('token', $token)
->where('expire_time', '>', time())->lock(true)->findOrEmpty();
if ($session->isEmpty()) {
JsonService::throw('登录已失效,请重新登录', [], -1);
}
return [$admin, $session];
}
private static function expire(int $adminId, ?string $token): array
{
$query = static function () use ($adminId, $token) {
$builder = AdminSession::where('admin_id', $adminId);
return $token === null ? $builder : $builder->where('token', $token);
};
$tokens = $query()->column('token');
$query()->update(['expire_time' => time() - 1, 'update_time' => time()]);
return $tokens;
}
private static function clearTokens(array $tokens): void
{
$cache = new AdminTokenCache();
foreach ($tokens as $token) {
$cache->deleteAdminInfo((string) $token);
}
}
}