Files
knowai/auth/session-manager.ts
2025-11-23 22:26:39 +08:00

94 lines
2.9 KiB
TypeScript
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.

/**
* 会话管理器
* 负责查询用户认证状态不主动管理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<boolean> {
try {
// 通过调用API验证认证状态
await this.getUserInfo();
return true;
} catch (error) {
// 如果认证失败触发session_expired事件
authEventManager.emit('session_expired', error);
return false;
}
}
/**
* 获取当前用户信息
* 幂等操作,每次都从服务器获取最新用户信息
* @returns 用户信息
* @throws 当获取用户信息失败时抛出错误
*/
async getUserInfo(): Promise<User> {
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);
}