new changes
This commit is contained in:
@@ -1,5 +1,20 @@
|
||||
const API_BASE = '/api/v1'
|
||||
|
||||
function formatFastApiDetail(detail: unknown): string | undefined {
|
||||
if (typeof detail === 'string') return detail
|
||||
if (Array.isArray(detail)) {
|
||||
return detail
|
||||
.map((item) => {
|
||||
if (item && typeof item === 'object' && 'msg' in item) {
|
||||
return String((item as { msg: string }).msg)
|
||||
}
|
||||
return JSON.stringify(item)
|
||||
})
|
||||
.join('; ')
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export async function apiRequest<T>(
|
||||
path: string,
|
||||
options: RequestInit = {}
|
||||
@@ -26,16 +41,26 @@ export async function apiRequest<T>(
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string) {
|
||||
const form = new FormData()
|
||||
form.append('username', username)
|
||||
form.append('password', password)
|
||||
// OAuth2 password flow uses application/x-www-form-urlencoded (RFC 6749).
|
||||
// multipart FormData can be mishandled by some proxies and is non-standard here.
|
||||
const body = new URLSearchParams()
|
||||
body.set('username', username)
|
||||
body.set('password', password)
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: body.toString(),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
throw new Error(err.detail || `Login failed`)
|
||||
const err = await res.json().catch(() => null)
|
||||
const detail = err ? formatFastApiDetail(err.detail) : undefined
|
||||
const msg =
|
||||
detail ||
|
||||
(err && typeof (err as { message?: string }).message === 'string'
|
||||
? (err as { message: string }).message
|
||||
: undefined) ||
|
||||
`Login failed (${res.status})`
|
||||
throw new Error(msg)
|
||||
}
|
||||
const data = await res.json()
|
||||
localStorage.setItem('token', data.access_token)
|
||||
|
||||
Reference in New Issue
Block a user