/** * 会话管理器 * 负责查询用户认证状态,不主动管理session * session完全由服务器端控制,前端只通过API查询状态 */ import type { ApiClient } from '@/api/types'; import type { User } from '@/types'; import type { StorageAdapter } from './types'; import { authEventManager } from './event-manager'; export class DefaultSessionManager { private readonly apiClient: ApiClient; private readonly storage: StorageAdapter; private currentUser: User | null = null; constructor(apiClient: ApiClient, storage: StorageAdapter) { this.apiClient = apiClient; this.storage = storage; } /** * 检查是否已认证 * 通过API调用验证用户认证状态,而不是直接访问cookie * @returns 是否已认证 */ async isAuthenticated(): Promise { try { // 通过调用API验证认证状态 await this.getUserInfo(); return true; } catch (error) { // 如果认证失败,触发session_expired事件 authEventManager.emit('session_expired', error); return false; } } /** * 获取当前用户信息 * 幂等操作,每次都从服务器获取最新用户信息 * @returns 用户信息 * @throws 当获取用户信息失败时抛出错误 */ async getUserInfo(): Promise { try { // API客户端的get方法已经返回解构后的数据,不需要访问.data const response = await this.apiClient.get<{ user: User }>('/auth/me'); this.currentUser = response.user; // 如果成功获取用户信息,触发session_authenticated事件 authEventManager.emit('session_authenticated', this.currentUser); return response.user; } catch (error) { this.currentUser = null; // 如果获取用户信息失败,触发session_expired事件 authEventManager.emit('session_expired', error); // 抛出错误,让调用者处理 throw error; } } /** * 清除本地缓存 * 不影响服务器端session,只清除前端缓存 */ clearCache(): void { this.currentUser = null; // 清除存储适配器中的所有项(如果支持) if ('clear' in this.storage && typeof this.storage.clear === 'function') { this.storage.clear(); } else { // 如果不支持clear方法,逐个删除已知项 const keys = ['user_preferences', 'ui_state']; // 示例键 keys.forEach(key => this.storage.removeItem(key)); } // 触发session_logout事件 authEventManager.emit('session_logout'); } } /** * 创建会话管理器 * @param apiClient API客户端 * @param storage 存储适配器,仅用于非敏感数据缓存 * @returns 会话管理器实例 */ export function createSessionManager( apiClient: ApiClient, storage: StorageAdapter ): DefaultSessionManager { return new DefaultSessionManager(apiClient, storage); }