You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.2 KiB

import axios from 'axios'
import type { AdminChangePasswordBody, AdminLoginBody, AdminLoginResult } from './types'
import { adminHttp } from './http'
/** POST /auth/login — 与 `routes/api.php` 中 `v1/admin` 分组一致 */
export async function adminLogin(body: AdminLoginBody): Promise<AdminLoginResult> {
try {
const { data } = await adminHttp.post<unknown>('/auth/login', body)
return unwrapLogin(data)
} catch (e) {
if (axios.isAxiosError(e)) {
const raw = e.response?.data
const d = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
const message =
(typeof d.message === 'string' ? d.message : '') ||
(d.errors && typeof d.errors === 'object'
? Object.values(d.errors as Record<string, string[]>).flat().join('\n')
: '') ||
e.message
throw new Error(message || '登录失败')
}
throw e
}
}
function unwrapLogin(raw: unknown): AdminLoginResult {
if (raw && typeof raw === 'object') {
const o = raw as Record<string, unknown>
const data = o.data as Record<string, unknown> | undefined
const token =
(typeof o.token === 'string' ? o.token : undefined) ??
(typeof o.access_token === 'string' ? o.access_token : undefined) ??
(data && typeof data.token === 'string' ? data.token : undefined)
if (typeof token === 'string') {
const userRaw = o.user ?? o.admin ?? data?.user
return {
token,
user: userRaw as AdminLoginResult['user'],
}
}
}
throw new Error('登录响应无效')
}
/** PUT /auth/password */
export async function changeAdminPassword(body: AdminChangePasswordBody): Promise<void> {
try {
await adminHttp.put('/auth/password', body)
} catch (e) {
if (axios.isAxiosError(e)) {
const raw = e.response?.data
const d = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}
const message =
(typeof d.message === 'string' ? d.message : '') ||
(d.errors && typeof d.errors === 'object'
? Object.values(d.errors as Record<string, string[]>).flat().join('\n')
: '') ||
e.message
throw new Error(message || '修改密码失败')
}
throw e
}
}