Files
dafuweng-saiadmin6.x/server/app/api/cache/AuthTokenCache.php

55 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace app\api\cache;
use support\think\Cache;
/**
* 按设备标识存储当前有效的 auth-token同一设备只保留最新一个旧 token 自动失效
*/
class AuthTokenCache
{
private static function prefix(): string
{
return config('api.auth_token_device_prefix', 'api:auth_token:');
}
/**
* 设置该设备当前有效的 auth-token会覆盖同设备之前的 token使旧 token 失效)
* @param string $device 设备标识,如 dice
* @param string $token 完整 auth-token 字符串
* @param int $ttl 过期时间(秒),应与 auth_token_exp 一致
*/
public static function setDeviceToken(string $device, string $token, int $ttl): bool
{
if ($device === '' || $ttl <= 0) {
return false;
}
$key = self::prefix() . $device;
return Cache::set($key, $token, $ttl);
}
/**
* 获取该设备当前有效的 auth-token不存在或已过期返回 null
*/
public static function getDeviceToken(string $device): ?string
{
if ($device === '') {
return null;
}
$key = self::prefix() . $device;
$value = Cache::get($key);
return $value !== null && $value !== '' ? (string) $value : null;
}
/**
* 校验请求中的 token 是否为该设备当前唯一有效 token
*/
public static function isCurrentToken(string $device, string $token): bool
{
$current = self::getDeviceToken($device);
return $current !== null && $current === $token;
}
}