/** * 页面登录态引导 * * SPA 化后由 src/main.ts 的路由守卫调用;本模块只做检查与 uid/username 恢复, * 不主动跳转(跳转统一由 router.beforeEach 返回 { name: 'login' })。 * - localStorage.uid 已存在(桌面注入 / 登录页已写入)→ 直接放行,零额外请求; * - 无 uid 但有 JWT → 调 /newApi/check_login 恢复 uid/username; * - 无 token 或校验失败 → 返回 false,由守卫跳转登录页。 */ import { get } from '@/shared/api/http' const AUTH_TOKEN_KEY = 'aiimage_auth_token' const UID_KEY = 'uid' interface CheckLoginData { userId?: number | string username?: string } /** 确保当前页面具备登录态;返回是否可继续进入页面 */ export async function ensureAuth(): Promise { if (typeof window === 'undefined') return true try { const rawUid = window.localStorage.getItem(UID_KEY) || '' if (rawUid && Number(rawUid) > 0) { return true } const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || '' if (!token) { return false } const response = await get<{ success: boolean; data?: CheckLoginData }>('/newApi/check_login') if (response?.success !== true || !response.data?.userId) { throw new Error('登录已失效') } window.localStorage.setItem(UID_KEY, String(response.data.userId)) if (response.data.username) { window.localStorage.setItem('username', String(response.data.username)) } return true } catch { // token 失效:清掉本地登录态(跳转交给路由守卫) try { window.localStorage.removeItem(AUTH_TOKEN_KEY) } catch { /* 忽略 */ } return false } } /** * 尽力恢复登录用户快照(ensureAuth 的"软"版本):有 token 时调 /newApi/check_login * 回写 uid/username,无 token 或失败静默返回 null、不跳转登录页(首页等不强制登录的场景用)。 */ export async function restoreLoginUser(): Promise<{ username?: string } | null> { if (typeof window === 'undefined') return null try { const rawUid = window.localStorage.getItem(UID_KEY) || '' if (rawUid && Number(rawUid) > 0) { // 已有 uid(桌面端注入或登录页已写)无需再查 return null } const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || '' if (!token) { return null } const response = await get<{ success: boolean; data?: CheckLoginData }>('/newApi/check_login') if (response?.success !== true || !response.data?.userId) { return null } window.localStorage.setItem(UID_KEY, String(response.data.userId)) if (response.data.username) { window.localStorage.setItem('username', String(response.data.username)) } return { username: response.data.username } } catch { return null } }