- 修复 initAuth 中错误的 cookie 解析方式,使用 getSessionUser() 正确读取 - 重构 auth store,提取公共方法消除代码重复 - 提取 setUserState/clearUserState 统一状态管理 - 提取 isAuthError 统一错误判断 - 提取 restoreUserFromStorage 恢复 localStorage 状态 - 提取 validateAndUpdateUser 统一验证逻辑 - 优化 fetchInterceptor,添加初始化标志避免在 initAuth 期间误触发登出 - 改进错误处理,区分认证错误和网络错误,避免网络错误导致误登出 - 优化 initAuth 逻辑,先恢复 localStorage 状态避免闪烁,再验证 cookie 代码从 178 行优化到 165 行,initAuth 从 87 行减少到 28 行,消除 40+ 行重复代码
51 lines
1.6 KiB
TypeScript
51 lines
1.6 KiB
TypeScript
// 保存原始的fetch函数
|
||
const originalFetch = window.fetch
|
||
|
||
// 标记是否正在初始化认证(避免在initAuth期间误触发登出)
|
||
let isInitializingAuth = false
|
||
|
||
// 导出函数,允许外部设置初始化状态
|
||
export function setInitializingAuth(value: boolean) {
|
||
isInitializingAuth = value
|
||
}
|
||
|
||
// 包装fetch函数,添加401/403错误处理
|
||
window.fetch = async function(...args: Parameters<typeof fetch>): Promise<Response> {
|
||
const response = await originalFetch(...args)
|
||
|
||
// 检查响应状态码(仅在401/403时处理)
|
||
if (response.status === 401 || response.status === 403) {
|
||
// 如果正在初始化认证,不自动登出(让initAuth自己处理)
|
||
if (isInitializingAuth) {
|
||
return response
|
||
}
|
||
|
||
// 延迟导入,确保pinia已初始化
|
||
try {
|
||
const { useAuthStore } = await import('../stores/auth')
|
||
const { default: router } = await import('../../app/router')
|
||
const authStore = useAuthStore()
|
||
|
||
// 如果用户已登录,执行登出操作
|
||
if (authStore.isLoggedIn) {
|
||
console.warn('检测到401/403错误,Cookie已过期,自动退出登录')
|
||
await authStore.logout()
|
||
|
||
// 跳转到登录页(避免重复跳转)
|
||
if (router.currentRoute.value.path !== '/login') {
|
||
router.push('/login')
|
||
}
|
||
}
|
||
} catch (error) {
|
||
// 如果store还未初始化,忽略错误(应用启动阶段)
|
||
// 这不会影响正常的API调用
|
||
}
|
||
}
|
||
|
||
return response
|
||
}
|
||
|
||
// 导出原始fetch(如果需要的话)
|
||
export { originalFetch as originalFetch }
|
||
|