Files
novalon-manage-system/novalon-manage-web/e2e/role-based-tests/shared/role-auth-manager.ts
T
张翔 68070886d9 feat: 实现认证辅助工具
- 创建 Token 管理器 RoleAuthManager
- 创建认证辅助类 AuthHelper
- 支持 Token 注入和真实登录两种模式
- 实现 Token 缓存机制
- 添加完整的单元测试(5个测试用例全部通过)
2026-04-04 20:54:03 +08:00

56 lines
1.6 KiB
TypeScript

import { RoleFactory } from '../roles/role-factory';
interface TokenCache {
token: string;
expiresAt: number;
}
export class RoleAuthManager {
private static tokenCache: Map<string, TokenCache> = 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<string> {
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<string> {
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);
}
}