重新登录或注册后清除掉原有用户的user-token保证只有一个用户能够登录
This commit is contained in:
47
server/app/api/cache/UserCache.php
vendored
47
server/app/api/cache/UserCache.php
vendored
@@ -131,4 +131,51 @@ class UserCache
|
||||
$val = Cache::get($key);
|
||||
return $val !== null && $val !== '';
|
||||
}
|
||||
|
||||
/** 当前有效 user-token 按用户存储的 key 前缀(重新登录/注册后覆盖,保证单用户单 token) */
|
||||
private static function currentTokenPrefix(): string
|
||||
{
|
||||
return config('api.user_token_current_prefix', 'api:user:current_token:');
|
||||
}
|
||||
|
||||
private static function userTokenExpire(): int
|
||||
{
|
||||
return (int) config('api.user_token_exp', 604800);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置该用户当前唯一有效的 user-token(登录/注册时调用,会覆盖该用户之前的 token)
|
||||
* @param int $userId 用户 ID
|
||||
* @param string $token 完整 user-token 字符串
|
||||
*/
|
||||
public static function setCurrentUserToken(int $userId, string $token): bool
|
||||
{
|
||||
if ($userId <= 0 || $token === '') {
|
||||
return false;
|
||||
}
|
||||
$key = self::currentTokenPrefix() . $userId;
|
||||
return Cache::set($key, $token, self::userTokenExpire());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取该用户当前在服务端登记的有效 user-token,不存在或已过期返回 null
|
||||
*/
|
||||
public static function getCurrentUserToken(int $userId): ?string
|
||||
{
|
||||
if ($userId <= 0) {
|
||||
return null;
|
||||
}
|
||||
$key = self::currentTokenPrefix() . $userId;
|
||||
$value = Cache::get($key);
|
||||
return $value !== null && $value !== '' ? (string) $value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验请求中的 token 是否为该用户当前唯一有效 token
|
||||
*/
|
||||
public static function isCurrentUserToken(int $userId, string $token): bool
|
||||
{
|
||||
$current = self::getCurrentUserToken($userId);
|
||||
return $current !== null && $current === $token;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user