import { RoleFactory } from '../roles/role-factory'; interface TokenCache { token: string; expiresAt: number; } export class RoleAuthManager { private static tokenCache: Map = new Map(); private static readonly API_BASE_URL = process.env.VITE_API_BASE_URL || 'http://localhost:8084'; private static readonly TOKEN_EXPIRY_BUFFER = 60000; // 1分钟缓冲 static async getRoleToken(roleName: string): Promise { const cached = this.tokenCache.get(roleName); if (cached && cached.expiresAt > Date.now() + this.TOKEN_EXPIRY_BUFFER) { return cached.token; } const role = RoleFactory.getRole(roleName); const token = await this.authenticateWithBackend(role.credentials); this.tokenCache.set(roleName, { token, expiresAt: Date.now() + 3600000 // 假设token有效期1小时 }); return token; } private static async authenticateWithBackend(credentials: { username: string; password: string }): Promise { const response = await fetch(`${this.API_BASE_URL}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(credentials), }); if (!response.ok) { throw new Error(`Authentication failed for user ${credentials.username}: ${response.statusText}`); } const data = await response.json(); return data.data?.token || data.token; } static clearCache(): void { this.tokenCache.clear(); } static clearRoleToken(roleName: string): void { this.tokenCache.delete(roleName); } }