53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
// ============================================================
|
|
// ZCLAW SaaS Admin — JWT Token 管理
|
|
// ============================================================
|
|
|
|
import type { AccountPublic } from './types'
|
|
|
|
const TOKEN_KEY = 'zclaw_admin_token'
|
|
const ACCOUNT_KEY = 'zclaw_admin_account'
|
|
|
|
/** 保存登录凭证 */
|
|
export function login(token: string, account: AccountPublic): void {
|
|
if (typeof window === 'undefined') return
|
|
localStorage.setItem(TOKEN_KEY, token)
|
|
localStorage.setItem(ACCOUNT_KEY, JSON.stringify(account))
|
|
}
|
|
|
|
/** 清除登录凭证 */
|
|
export function logout(): void {
|
|
if (typeof window === 'undefined') return
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
localStorage.removeItem(ACCOUNT_KEY)
|
|
}
|
|
|
|
/** 清除认证状态(用于 Token 验证失败时) */
|
|
export function clearAuth(): void {
|
|
if (typeof window === 'undefined') return
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
localStorage.removeItem(ACCOUNT_KEY)
|
|
}
|
|
|
|
/** 获取 JWT token */
|
|
export function getToken(): string | null {
|
|
if (typeof window === 'undefined') return null
|
|
return localStorage.getItem(TOKEN_KEY)
|
|
}
|
|
|
|
/** 获取当前登录用户信息 */
|
|
export function getAccount(): AccountPublic | null {
|
|
if (typeof window === 'undefined') return null
|
|
const raw = localStorage.getItem(ACCOUNT_KEY)
|
|
if (!raw) return null
|
|
try {
|
|
return JSON.parse(raw) as AccountPublic
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/** 是否已认证 */
|
|
export function isAuthenticated(): boolean {
|
|
return !!getToken()
|
|
}
|