diff --git a/application/common/library/token/driver/Cache.php b/application/common/library/token/driver/Cache.php new file mode 100644 index 00000000..63322f6a --- /dev/null +++ b/application/common/library/token/driver/Cache.php @@ -0,0 +1,132 @@ +options = $options; + + // 获取缓存配置 + $cacheName = isset($options['cache']) ? $options['cache'] : 'cache'; + $cacheConfig = config($cacheName); + + // 初始化缓存实例 + $this->cache = Caches::connect($cacheConfig ?: []); + } + + /** + * 获取Token + * @param string $token Token标识 + * @return array|false + */ + public function get($token) + { + if (!$token) { + return false; + } + + $key = $this->getCacheKey($token); + $data = $this->cache->get($key); + + if (!$data) { + return false; + } + + // 检查是否过期 + if (isset($data['expire_time']) && $data['expire_time'] < time()) { + $this->delete($token); + return false; + } + + return $data; + } + + /** + * 设置Token + * @param string $token Token标识 + * @param mixed $user_id 用户ID + * @param int $expire 过期时间(秒) + * @return bool + */ + public function set($token, $user_id, $expire = 0) + { + if (!$token) { + return false; + } + + $data = [ + 'token' => $token, + 'user_id' => $user_id, + 'expire_time' => $expire > 0 ? time() + $expire : 0, + 'create_time' => time(), + ]; + + $key = $this->getCacheKey($token); + + if ($expire > 0) { + return $this->cache->set($key, $data, $expire); + } else { + return $this->cache->set($key, $data); + } + } + + /** + * 删除Token + * @param string $token Token标识 + * @return bool + */ + public function delete($token) + { + if (!$token) { + return false; + } + + $key = $this->getCacheKey($token); + return $this->cache->rm($key); + } + + /** + * 清除用户的所有Token + * @param mixed $user_id 用户ID + * @return bool + */ + public function clear($user_id) + { + // 注意:缓存驱动可能无法直接按用户ID清理所有Token + // 如果需要此功能,建议使用Redis驱动或在业务层维护Token列表 + // 这里简单实现,实际项目中可能需要更复杂的逻辑 + return true; + } + + /** + * 获取缓存键名 + * @param string $token Token标识 + * @return string + */ + protected function getCacheKey($token) + { + $prefix = isset($this->options['prefix']) ? $this->options['prefix'] : 'fastadmin:token:'; + return $prefix . $token; + } +} \ No newline at end of file diff --git a/application/config.php b/application/config.php index 87122578..c4e8b93f 100644 --- a/application/config.php +++ b/application/config.php @@ -272,7 +272,7 @@ return [ // +---------------------------------------------------------------------- 'token' => [ // 驱动方式 - 'type' => 'redis', + 'type' => 'cache', // 缓存前缀 'key' => 'Ydkn5NyZBMoCshDIXSRcQrHGefjt6iax', // 加密方式