[接口v1]对接平台API-鉴权authtoken接口和getGameUrl接口
This commit is contained in:
83
server/app/api/cache/AuthTokenCache.php
vendored
Normal file
83
server/app/api/cache/AuthTokenCache.php
vendored
Normal file
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\api\cache;
|
||||
|
||||
use support\think\Cache;
|
||||
|
||||
/**
|
||||
* 平台 auth-token Redis 缓存
|
||||
* 用于 /api/v1/authToken 鉴权接口颁发的 token 存储与校验
|
||||
*/
|
||||
class AuthTokenCache
|
||||
{
|
||||
private static function devicePrefix(): string
|
||||
{
|
||||
return config('api.auth_token_device_prefix', 'api:auth_token:');
|
||||
}
|
||||
|
||||
private static function tokenPrefix(): string
|
||||
{
|
||||
return config('api.auth_token_prefix', 'api:auth_token:t:');
|
||||
}
|
||||
|
||||
private static function expire(): int
|
||||
{
|
||||
return (int) config('api.auth_token_exp', 86400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 存储 auth-token(同一 agent_id 只保留最新一个)
|
||||
* @param string $agentId 代理 ID
|
||||
* @param string $token 生成的 auth-token
|
||||
*/
|
||||
public static function setToken(string $agentId, string $token): bool
|
||||
{
|
||||
if ($agentId === '' || $token === '') {
|
||||
return false;
|
||||
}
|
||||
$exp = self::expire();
|
||||
if ($exp <= 0) {
|
||||
return false;
|
||||
}
|
||||
$oldToken = Cache::get(self::devicePrefix() . $agentId);
|
||||
if ($oldToken !== null && $oldToken !== '') {
|
||||
Cache::delete(self::tokenPrefix() . $oldToken);
|
||||
}
|
||||
Cache::set(self::tokenPrefix() . $token, $agentId, $exp);
|
||||
Cache::set(self::devicePrefix() . $agentId, $token, $exp);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 agent_id 获取当前有效的 token,不存在或已过期返回 null
|
||||
*/
|
||||
public static function getTokenByAgentId(string $agentId): ?string
|
||||
{
|
||||
if ($agentId === '') {
|
||||
return null;
|
||||
}
|
||||
$val = Cache::get(self::devicePrefix() . $agentId);
|
||||
return $val !== null && $val !== '' ? (string) $val : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 auth-token 获取 agent_id,不存在或已过期返回 null
|
||||
*/
|
||||
public static function getAgentIdByToken(string $token): ?string
|
||||
{
|
||||
if ($token === '') {
|
||||
return null;
|
||||
}
|
||||
$val = Cache::get(self::tokenPrefix() . $token);
|
||||
return $val !== null && $val !== '' ? (string) $val : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 auth-token 是否有效
|
||||
*/
|
||||
public static function isValidToken(string $token): bool
|
||||
{
|
||||
return self::getAgentIdByToken($token) !== null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user