搭建用户体系

This commit is contained in:
2026-07-03 23:40:33 +08:00
parent 37a9f865ed
commit 2df19fcd02
40 changed files with 2622 additions and 0 deletions
+119
View File
@@ -0,0 +1,119 @@
const API_BASE = import.meta.env.VITE_API_BASE_URL || ''
export interface ApiResponse<T> {
success?: boolean
data?: T
error?: string
}
export interface UserInfo {
id: string
username: string
email?: string
role: 'system_admin' | 'admin' | 'user' | 'guest'
status: string
created_at: string
}
export interface Role {
id: number
name: 'system_admin' | 'admin' | 'user' | 'guest'
description?: string
permissions: string[]
created_at: string
}
export interface AuthResponse {
token: string
user: UserInfo
}
export function getToken(): string | null {
try {
return localStorage.getItem('access_token')
} catch {
return null
}
}
export function setToken(token: string) {
localStorage.setItem('access_token', token)
}
export function removeToken() {
localStorage.removeItem('access_token')
}
async function request<T>(
path: string,
options: RequestInit = {},
): Promise<T> {
const url = `${API_BASE}${path}`
const token = getToken()
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(options.headers as Record<string, string>),
}
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
const res = await fetch(url, {
...options,
headers,
})
let data: any
try {
data = await res.json()
} catch {
data = {}
}
if (!res.ok) {
const msg = data.error || data.message || `HTTP ${res.status}`
throw new Error(msg)
}
return data as T
}
export const api = {
publicInfo: () =>
request<{ message: string; guest_allowed: boolean }>('/api/public'),
register: (body: { username: string; email?: string; password: string }) =>
request<AuthResponse>('/api/auth/register', {
method: 'POST',
body: JSON.stringify(body),
}),
login: (body: { username: string; password: string }) =>
request<AuthResponse>('/api/auth/login', {
method: 'POST',
body: JSON.stringify(body),
}),
me: () => request<UserInfo>('/api/auth/me'),
logout: () => request<{ message: string }>('/api/auth/logout', { method: 'POST' }),
listUsers: () => request<UserInfo[]>('/api/admin/users'),
createUser: (body: { username: string; email?: string; password: string; role?: string }) =>
request<UserInfo>('/api/admin/users', {
method: 'POST',
body: JSON.stringify(body),
}),
updateUser: (id: string, body: Partial<{ email: string; role: string; status: string }>) =>
request<UserInfo>(`/api/admin/users/${id}`, {
method: 'PUT',
body: JSON.stringify(body),
}),
deleteUser: (id: string) =>
request<{ message: string }>(`/api/admin/users/${id}`, { method: 'DELETE' }),
listRoles: () => request<Role[]>('/api/admin/roles'),
}