优化登录接口以及中间件

This commit is contained in:
2026-03-05 16:20:18 +08:00
parent e5f83846b3
commit 39955a17a8
12 changed files with 268 additions and 516 deletions

View File

@@ -178,4 +178,52 @@ class UserCache
$current = self::getCurrentUserToken($userId);
return $current !== null && $current === $token;
}
/** 按 username 的登录会话 key 前缀token 中间件:存在即视为已登录) */
private static function sessionUsernamePrefix(): string
{
return config('api.session_username_prefix', 'api:user:session:');
}
private static function sessionExpire(): int
{
return (int) config('api.session_expire', 604800);
}
/** 设置 username 当前有效 tokenJWT重新登录会覆盖实现单点登录 */
public static function setSessionByUsername(string $username, string $token): bool
{
if ($username === '' || $token === '') {
return false;
}
$key = self::sessionUsernamePrefix() . $username;
return Cache::set($key, $token, self::sessionExpire());
}
/** 获取 username 当前在服务端登记的有效 tokenJWT不存在返回 null */
public static function getSessionTokenByUsername(string $username): ?string
{
if ($username === '') {
return null;
}
$key = self::sessionUsernamePrefix() . $username;
$val = Cache::get($key);
return $val !== null && $val !== '' ? (string) $val : null;
}
/** 检查 username 是否已有登录会话Redis 中是否存在当前 token */
public static function hasSessionByUsername(string $username): bool
{
return self::getSessionTokenByUsername($username) !== null;
}
/** 删除 username 登录会话(退出登录时调用) */
public static function deleteSessionByUsername(string $username): bool
{
if ($username === '') {
return false;
}
$key = self::sessionUsernamePrefix() . $username;
return Cache::delete($key);
}
}