- 新增认证 API、类型与本地会话存储 - 登录页改为真实账号密码登录并移除验证码 - 请求拦截器改用 X-Token 并处理 401 跳转 - 添加 Vite /api 开发代理配置
60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
import type { AuthenticatedUser, LoginResponse } from '@/types/auth'
|
|
|
|
export const AUTH_TOKEN_KEY = 'token'
|
|
export const AUTH_USER_KEY = 'userInfo'
|
|
export const AUTH_EXPIRES_AT_KEY = 'tokenExpiresAt'
|
|
|
|
export interface StoredAuthSession {
|
|
token: string
|
|
user: AuthenticatedUser | null
|
|
expiresAt: string | null
|
|
}
|
|
|
|
function readStoredUser(): AuthenticatedUser | null {
|
|
const rawUser = localStorage.getItem(AUTH_USER_KEY)
|
|
|
|
if (!rawUser) {
|
|
return null
|
|
}
|
|
|
|
try {
|
|
return JSON.parse(rawUser) as AuthenticatedUser
|
|
} catch {
|
|
localStorage.removeItem(AUTH_USER_KEY)
|
|
return null
|
|
}
|
|
}
|
|
|
|
export function readStoredAuthSession(): StoredAuthSession | null {
|
|
const token = localStorage.getItem(AUTH_TOKEN_KEY)
|
|
|
|
if (!token) {
|
|
return null
|
|
}
|
|
|
|
const expiresAt = localStorage.getItem(AUTH_EXPIRES_AT_KEY)
|
|
|
|
if (expiresAt && Date.parse(expiresAt) <= Date.now()) {
|
|
clearAuthStorage()
|
|
return null
|
|
}
|
|
|
|
return {
|
|
token,
|
|
user: readStoredUser(),
|
|
expiresAt,
|
|
}
|
|
}
|
|
|
|
export function saveAuthSession(session: LoginResponse) {
|
|
localStorage.setItem(AUTH_TOKEN_KEY, session.token)
|
|
localStorage.setItem(AUTH_EXPIRES_AT_KEY, session.expiresAt)
|
|
localStorage.setItem(AUTH_USER_KEY, JSON.stringify(session.user))
|
|
}
|
|
|
|
export function clearAuthStorage() {
|
|
localStorage.removeItem(AUTH_TOKEN_KEY)
|
|
localStorage.removeItem(AUTH_EXPIRES_AT_KEY)
|
|
localStorage.removeItem(AUTH_USER_KEY)
|
|
}
|