feat: 增加了登录选项

This commit is contained in:
2025-07-11 16:36:28 +08:00
parent d88c710606
commit b4bb563782
8 changed files with 790 additions and 129 deletions

93
src/utils/AuthManager.ts Normal file
View File

@@ -0,0 +1,93 @@
import { DataClient } from '@/APIClient'
export class AuthManager {
// 存储token到localStorage
public static setToken(token: string): void {
localStorage.setItem('authToken', token)
}
// 从localStorage获取token
public static getToken(): string | null {
return localStorage.getItem('authToken')
}
// 清除token
public static clearToken(): void {
localStorage.removeItem('authToken')
}
// 检查是否已认证
public static async isAuthenticated(): Promise<boolean> {
return await AuthManager.verifyToken()
}
// 为HTTP请求添加Authorization header
public static addAuthHeader(client: any): void {
const token = AuthManager.getToken()
if (token && client.http) {
const originalFetch = client.http.fetch
client.http.fetch = (url: RequestInfo, init?: RequestInit) => {
if (!init) init = {}
if (!init.headers) init.headers = {}
// 添加Authorization header
if (typeof init.headers === 'object' && init.headers !== null) {
(init.headers as any)['Authorization'] = `Bearer ${token}`
}
return originalFetch(url, init)
}
}
}
// 创建已配置认证的API客户端
public static createAuthenticatedClient(): DataClient {
const client = new DataClient()
AuthManager.addAuthHeader(client)
return client
}
// 登录函数
public static async login(username: string, password: string): Promise<boolean> {
try {
const client = new DataClient()
const token = await client.login(username, password)
if (token) {
AuthManager.setToken(token)
// 验证token
const authClient = AuthManager.createAuthenticatedClient()
await authClient.testAuth()
return true
}
return false
} catch (error) {
AuthManager.clearToken()
throw error
}
}
// 登出函数
public static logout(): void {
AuthManager.clearToken()
}
// 验证当前token是否有效
public static async verifyToken(): Promise<boolean> {
try {
const token = AuthManager.getToken()
if (!token) {
return false
}
const client = AuthManager.createAuthenticatedClient()
await client.testAuth()
return true
} catch (error) {
AuthManager.clearToken()
return false
}
}
}