更新登录功能
This commit is contained in:
39
src/api/token.ts
Normal file
39
src/api/token.ts
Normal 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))
|
||||
}
|
||||
Reference in New Issue
Block a user