feat: add frontend auth shell

This commit is contained in:
hailin
2026-07-01 14:15:26 +08:00
parent 953f126277
commit 4925285cf3
12 changed files with 664 additions and 40 deletions

View File

@@ -1,17 +1,44 @@
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000/api'
let csrfToken: string | null = null
async function getCsrfToken() {
if (!csrfToken) {
const response = await fetch(`${API_BASE_URL}/accounts/auth/csrf`, {
credentials: 'include'
})
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`)
}
const data = (await response.json()) as { csrfToken: string }
csrfToken = data.csrfToken
}
return csrfToken
}
export async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers)
if (init?.body && !headers.has('content-type')) {
headers.set('content-type', 'application/json')
}
const method = init?.method?.toUpperCase() ?? 'GET'
if (!['GET', 'HEAD', 'OPTIONS'].includes(method) && !headers.has('x-csrftoken')) {
headers.set('x-csrftoken', await getCsrfToken())
}
const response = await fetch(`${API_BASE_URL}${path}`, {
headers: {
'content-type': 'application/json',
...init?.headers
},
...init
...init,
credentials: 'include',
headers
})
if (!response.ok) {
throw new Error(`API request failed: ${response.status}`)
}
if (response.status === 204) {
return undefined as T
}
return response.json() as Promise<T>
}