95 lines
2.3 KiB
TypeScript
95 lines
2.3 KiB
TypeScript
export interface AuthCredentials {
|
|
username: string
|
|
password: string
|
|
}
|
|
|
|
export interface AuthUser {
|
|
id: string
|
|
username: string
|
|
role: "admin" | "superadmin"
|
|
token: string
|
|
}
|
|
|
|
export class ClientAuthService {
|
|
private static instance: ClientAuthService
|
|
private storageKey = "auth-user"
|
|
|
|
// 默认凭据
|
|
private defaultCredentials = {
|
|
admin: { username: "admin", password: "admin123" },
|
|
superadmin: { username: "superadmin", password: "super123" },
|
|
}
|
|
|
|
static getInstance(): ClientAuthService {
|
|
if (!ClientAuthService.instance) {
|
|
ClientAuthService.instance = new ClientAuthService()
|
|
}
|
|
return ClientAuthService.instance
|
|
}
|
|
|
|
async login(credentials: AuthCredentials, role: "admin" | "superadmin"): Promise<AuthUser | null> {
|
|
const defaultCred = this.defaultCredentials[role]
|
|
|
|
if (credentials.username === defaultCred.username && credentials.password === defaultCred.password) {
|
|
const user: AuthUser = {
|
|
id: `${role}_${Date.now()}`,
|
|
username: credentials.username,
|
|
role,
|
|
token: `token_${role}_${Date.now()}`,
|
|
}
|
|
|
|
if (typeof window !== "undefined") {
|
|
try {
|
|
localStorage.setItem(this.storageKey, JSON.stringify(user))
|
|
} catch (error) {
|
|
console.error("Failed to save auth user:", error)
|
|
}
|
|
}
|
|
|
|
return user
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
getCurrentUser(): AuthUser | null {
|
|
if (typeof window === "undefined") return null
|
|
|
|
try {
|
|
const stored = localStorage.getItem(this.storageKey)
|
|
if (stored) {
|
|
return JSON.parse(stored)
|
|
}
|
|
} catch (error) {
|
|
console.error("Failed to get current user:", error)
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
logout(): void {
|
|
if (typeof window === "undefined") return
|
|
|
|
try {
|
|
localStorage.removeItem(this.storageKey)
|
|
} catch (error) {
|
|
console.error("Failed to logout:", error)
|
|
}
|
|
}
|
|
|
|
isAuthenticated(): boolean {
|
|
return this.getCurrentUser() !== null
|
|
}
|
|
|
|
hasRole(role: "admin" | "superadmin"): boolean {
|
|
const user = this.getCurrentUser()
|
|
return user?.role === role
|
|
}
|
|
|
|
updateCredentials(role: "admin" | "superadmin", credentials: AuthCredentials): void {
|
|
this.defaultCredentials[role] = credentials
|
|
}
|
|
}
|
|
|
|
export const clientAuthService = ClientAuthService.getInstance()
|