更新登录功能

This commit is contained in:
Eamon
2026-08-13 18:28:20 +08:00
parent 115ee3bfeb
commit 4235458bea
25 changed files with 1900 additions and 873 deletions

39
src/api/token.ts Normal file
View File

@@ -0,0 +1,39 @@
const AUTH_EVENT = "auth-change"
const TOKEN_KEY = "auth_token"
const USER_KEY = "auth_user"
export function readCookie(name: string): string | null {
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`))
return match ? decodeURIComponent(match[1]) : null
}
export function getUserToken(): string | null {
return localStorage.getItem(TOKEN_KEY)
}
export function getUserInfo<T = unknown>(): T | null {
const raw = localStorage.getItem(USER_KEY)
if (!raw) return null
try {
return JSON.parse(raw) as T
} catch {
return null
}
}
export function isAuthed(): boolean {
return getUserToken() !== null
}
export function setSession(token: string, userInfo: unknown) {
localStorage.setItem(TOKEN_KEY, token)
localStorage.setItem(USER_KEY, JSON.stringify(userInfo))
window.dispatchEvent(new Event(AUTH_EVENT))
}
export function clearSession() {
localStorage.removeItem(TOKEN_KEY)
localStorage.removeItem(USER_KEY)
window.dispatchEvent(new Event(AUTH_EVENT))
}