Files
ai-agent/web/lib/auth.ts
T

64 lines
1.2 KiB
TypeScript
Raw Normal View History

2026-04-09 10:01:23 +08:00
export type AuthUser = {
id: number
username: string
nickname: string
avatar: string
status: number
roles: string[]
}
export type AuthSession = {
accessToken: string
expiresAt?: string
user: AuthUser
permissions: string[]
roles: string[]
}
2026-04-26 20:04:54 +08:00
const SESSION_STORAGE_KEY = "cs-ai-agent-session"
2026-04-30 18:10:01 +08:00
export const AUTH_SESSION_EXPIRED_EVENT = "cs-ai-agent-auth-expired"
2026-04-09 10:01:23 +08:00
function hasWindow() {
return typeof window !== "undefined"
}
export function readSession(): AuthSession | null {
if (!hasWindow()) {
return null
}
const raw = window.localStorage.getItem(SESSION_STORAGE_KEY)
if (!raw) {
return null
}
try {
return JSON.parse(raw) as AuthSession
} catch {
window.localStorage.removeItem(SESSION_STORAGE_KEY)
return null
}
}
export function writeSession(session: AuthSession) {
if (!hasWindow()) {
return
}
window.localStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(session))
}
export function clearSession() {
if (!hasWindow()) {
return
}
window.localStorage.removeItem(SESSION_STORAGE_KEY)
}
2026-04-30 18:10:01 +08:00
export function expireSession() {
if (!hasWindow()) {
return
}
clearSession()
window.dispatchEvent(new Event(AUTH_SESSION_EXPIRED_EVENT))
}