9adafb1354
后台登录框原来预填了 sundynix/sundynix,等于把凭证写在页面上,去掉。 令牌改为 access(2h) + refresh 两段式: - 新表 sundynix_refresh_tokens,只存 sha256,明文只在签发时返回一次 - 有效期:小程序 30 天、后台 7 天 - 新接口 /api/auth/refresh|logout、/api/admin/refresh|logout 安全约定: - 每次续期都轮换刷新令牌,旧的立即作废 - 作废后 60 秒内再到达算并发重试放行,超过则判定泄露、吊销该账号全部会话 - 主动退出与被连坐吊销的令牌不吃宽限期,否则「吊销全部」形同虚设 - 禁用用户时一并吊销刷新令牌,最多 2 小时彻底失去访问 两端请求层都做了单飞续期:并发请求同时 401 只发一次 refresh, 否则刷新令牌会被并发轮换掉互相打架。小程序续期失败回退 wx.login, 登录/续期请求标 noAuthRetry,避免登录失败(同样返回 40100)触发自我套娃。 顺带修掉 vite 代理仍指向 8080 的遗留(端口早已改 9090)。 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
150 lines
5.4 KiB
TypeScript
150 lines
5.4 KiB
TypeScript
import axios from 'axios'
|
|
|
|
const TOKEN_KEY = 'pets_admin_token'
|
|
const REFRESH_KEY = 'pets_admin_refresh'
|
|
|
|
export function getToken() {
|
|
return localStorage.getItem(TOKEN_KEY) || ''
|
|
}
|
|
export function getRefreshToken() {
|
|
return localStorage.getItem(REFRESH_KEY) || ''
|
|
}
|
|
export function setToken(t: string, refresh?: string) {
|
|
localStorage.setItem(TOKEN_KEY, t)
|
|
if (refresh) localStorage.setItem(REFRESH_KEY, refresh)
|
|
}
|
|
export function clearToken() {
|
|
localStorage.removeItem(TOKEN_KEY)
|
|
localStorage.removeItem(REFRESH_KEY)
|
|
}
|
|
|
|
const http = axios.create({ baseURL: '/api' })
|
|
|
|
http.interceptors.request.use((cfg) => {
|
|
const t = getToken()
|
|
if (t) cfg.headers.Authorization = `Bearer ${t}`
|
|
return cfg
|
|
})
|
|
|
|
// access token 只有 2 小时,过期后拿 refresh token 换新的。
|
|
// 用单飞(single-flight)保证并发请求只触发一次刷新,否则刷新令牌会被并发轮换掉。
|
|
let refreshing: Promise<string> | null = null
|
|
|
|
function refreshAccessToken(): Promise<string> {
|
|
if (!refreshing) {
|
|
const rt = getRefreshToken()
|
|
refreshing = (
|
|
rt
|
|
? axios.post('/api/admin/refresh', { refresh_token: rt }).then((r) => {
|
|
const body = r.data
|
|
if (!body || body.code !== 0) throw new Error(body?.message || '续期失败')
|
|
setToken(body.data.token, body.data.refresh_token)
|
|
return body.data.token as string
|
|
})
|
|
: Promise.reject(new Error('没有刷新令牌'))
|
|
).finally(() => {
|
|
refreshing = null
|
|
})
|
|
}
|
|
return refreshing
|
|
}
|
|
|
|
function logout() {
|
|
clearToken()
|
|
if (location.pathname !== '/admin/login') location.href = '/admin/login'
|
|
}
|
|
|
|
// 这几个接口本身就可能返回 40100(密码错、刷新令牌失效),不能再触发刷新,否则会绕圈
|
|
const NO_REFRESH = ['/admin/login', '/admin/refresh', '/admin/logout']
|
|
|
|
// 统一响应 {code,message,data}:成功返回 data,失败抛错
|
|
http.interceptors.response.use(
|
|
async (resp) => {
|
|
const body = resp.data
|
|
if (body && typeof body === 'object' && 'code' in body) {
|
|
if (body.code === 0) return body.data
|
|
if (body.code === 40100) {
|
|
const cfg = resp.config as typeof resp.config & { _retried?: boolean }
|
|
const skip = NO_REFRESH.some((p) => (cfg.url || '').startsWith(p))
|
|
if (!skip && !cfg._retried) {
|
|
cfg._retried = true
|
|
try {
|
|
const t = await refreshAccessToken()
|
|
cfg.headers.Authorization = `Bearer ${t}`
|
|
return await http.request(cfg)
|
|
} catch {
|
|
/* 续期失败,落到下面退出登录 */
|
|
}
|
|
}
|
|
if (!skip) logout()
|
|
}
|
|
return Promise.reject(new Error(body.message || '请求失败'))
|
|
}
|
|
return body
|
|
},
|
|
(err) => Promise.reject(err),
|
|
)
|
|
|
|
export interface Page<T> {
|
|
list: T[]
|
|
total: number
|
|
page: number
|
|
page_size: number
|
|
}
|
|
|
|
export const api = {
|
|
login: (username: string, password: string) =>
|
|
http.post<any, { token: string; refresh_token: string; expires_in: number; admin: any }>(
|
|
'/admin/login',
|
|
{ username, password },
|
|
),
|
|
logout: () => http.post('/admin/logout', { refresh_token: getRefreshToken() }),
|
|
me: () => http.get<any, any>('/admin/me'),
|
|
stats: () => http.get<any, { users: number; pets: number; posts: number; records: number }>('/admin/stats'),
|
|
|
|
users: (params: any) => http.get<any, Page<any>>('/admin/users', { params }),
|
|
setUserDisabled: (id: number, disabled: boolean) =>
|
|
http.put(`/admin/users/${id}/disabled`, { disabled }),
|
|
|
|
pets: (params: any) => http.get<any, Page<any>>('/admin/pets', { params }),
|
|
|
|
posts: (params: any) => http.get<any, Page<any>>('/admin/posts', { params }),
|
|
setPostStatus: (id: number, status: string) => http.put(`/admin/posts/${id}/status`, { status }),
|
|
|
|
comments: (params: any) => http.get<any, Page<any>>('/admin/comments', { params }),
|
|
deleteComment: (id: number) => http.delete(`/admin/comments/${id}`),
|
|
|
|
articles: (params: any) => http.get<any, Page<any>>('/admin/articles', { params }),
|
|
saveArticle: (a: any) => http.post('/admin/articles', a),
|
|
deleteArticle: (id: number) => http.delete(`/admin/articles/${id}`),
|
|
|
|
memberships: (params: any) => http.get<any, Page<any>>('/admin/memberships', { params }),
|
|
|
|
careTemplateMeta: () => http.get<any, any>('/admin/care-templates/meta'),
|
|
careTemplate: (species: string, stage: string) =>
|
|
http.get<any, { species: string; stage: string; items: any[] }>('/admin/care-templates', {
|
|
params: { species, stage },
|
|
}),
|
|
saveCareTemplate: (species: string, stage: string, items: any[]) =>
|
|
http.put<any, { items: any[] }>('/admin/care-templates', { species, stage, items }),
|
|
genCareTemplate: (species: string, stage: string) =>
|
|
http.post<any, { species: string; stage: string; items: any[] }>('/admin/care-templates/generate', {
|
|
species,
|
|
stage,
|
|
}),
|
|
|
|
feedback: (params: any) => http.get<any, Page<any>>('/admin/feedback', { params }),
|
|
setFeedbackHandled: (id: string, handled: boolean) =>
|
|
http.put(`/admin/feedback/${id}/handled`, { handled }),
|
|
|
|
communityBot: () =>
|
|
http.get<any, { enabled: boolean; daily_count: number; start_hour: number; end_hour: number }>(
|
|
'/admin/community-bot',
|
|
),
|
|
saveCommunityBot: (c: any) => http.put<any, any>('/admin/community-bot', c),
|
|
genCommunityPosts: (count: number) =>
|
|
http.post<any, { made: number }>('/admin/community-bot/generate', { count }),
|
|
}
|
|
|
|
export default http
|