2026-02-14 20:06:38 +08:00
|
|
|
import type { useAuthStore } from '@/stores/auth'
|
|
|
|
|
import { log } from '@/utils/logger'
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 判断错误是否为网络错误
|
|
|
|
|
*/
|
2026-02-22 00:43:41 +08:00
|
|
|
function isNetworkError(error: unknown): boolean {
|
|
|
|
|
const err = error as { response?: unknown; message?: string } | null
|
|
|
|
|
return !err?.response || err?.message?.includes('Network') || err?.message?.includes('timeout') || false
|
2026-02-14 20:06:38 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 确保用户信息已加载。如果有 token 但未加载用户信息,尝试获取。
|
|
|
|
|
* @returns true 如果用户已认证,false 如果认证失败
|
|
|
|
|
*/
|
|
|
|
|
export async function ensureUserLoaded(
|
|
|
|
|
authStore: ReturnType<typeof useAuthStore>
|
|
|
|
|
): Promise<boolean> {
|
2026-09-04 03:45:52 +08:00
|
|
|
if (!authStore.token) {
|
|
|
|
|
await authStore.restoreSession()
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-14 20:06:38 +08:00
|
|
|
if (authStore.token && !authStore.user) {
|
|
|
|
|
try {
|
|
|
|
|
await authStore.fetchCurrentUser()
|
2026-02-22 00:43:41 +08:00
|
|
|
} catch (error: unknown) {
|
|
|
|
|
const err = error as { response?: { status?: number }; message?: string }
|
2026-02-14 20:06:38 +08:00
|
|
|
// 区分网络错误和认证错误
|
|
|
|
|
if (isNetworkError(error)) {
|
|
|
|
|
log.warn('Network error while fetching user info, keeping session', {
|
2026-02-22 00:43:41 +08:00
|
|
|
error: err?.message
|
2026-02-14 20:06:38 +08:00
|
|
|
})
|
2026-02-22 00:43:41 +08:00
|
|
|
} else if (err.response?.status === 401) {
|
2026-02-14 20:06:38 +08:00
|
|
|
log.info('Authentication failed, clearing session')
|
2026-03-17 16:34:09 +08:00
|
|
|
await authStore.logout()
|
2026-02-14 20:06:38 +08:00
|
|
|
} else {
|
2026-02-22 00:43:41 +08:00
|
|
|
log.warn('Failed to fetch user info, but keeping session', { error: err?.message })
|
2026-02-14 20:06:38 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return !!authStore.token
|
|
|
|
|
}
|