import { computed, Injectable, signal } from '@angular/core'; import { Me } from './api/models'; const TOKEN_KEY = 'fmode_session_token'; const ME_KEY = 'fmode_me'; /** session 过期时间(ISO 字符串) */ const EXPIRES_KEY = 'fmode_session_expires_at'; /** * 会话状态(登录态 / 身份)—— 全项目唯一持有者 * * 依据《数据访问层设计.md》§五。约束: * · token 与 me 的持久化只在此处发生 * · `me()` 为 null 即「未登录」;**禁止**用 `as any` 伪造身份(存量反模式) * · `logout()` 必须清干净(含旧版兼容键,见 FR-16) */ @Injectable({ providedIn: 'root' }) export class SessionService { private readonly _token = signal(this.read(TOKEN_KEY)); private readonly _me = signal(this.readJson(ME_KEY)); /* * session 过期时间(2026-11-12)。 * 用 signal 而非普通字段:过期与否会影响 `isLoggedIn`,界面要能随之重算。 */ private readonly _expiresAt = signal(this.read(EXPIRES_KEY)); /** * 会话失效计数器(2026-11-27) * * ## 为什么需要 * * 原来服务端返回 401 时,`parse-api` 只**抛一个错误文本**, * 上层 catch 后显示「登录已失效,请重新登录」——但**页面不跳转**, * 用户停留在原页面反复失败,不知道要重新登录。 * * 现在任何地方发现 401 都调 `expire()`,根组件监听本信号并跳登录页。 * * ## 为什么用计数器而不是布尔 * * 布尔 `true` 只能触发一次;用户重新登录后如果再次失效, * 需要能**再次**触发。用递增计数器,每次 +1 都是新事件。 */ private readonly _expiredTick = signal(0); readonly expiredTick = this._expiredTick.asReadonly(); readonly token = this._token.asReadonly(); readonly me = this._me.asReadonly(); readonly expiresAt = this._expiresAt.asReadonly(); /** * 本地是否已过期。 * * 🔴 只做**快速判断**,不是唯一真相:真正的失效以服务端 401 为准。 * 拿不到 `expiresAt`(老登录态 / 接口不可用)时视为「未过期」, * 保持原行为,不把已有用户踢下线。 */ readonly isExpired = computed(() => { const e = this._expiresAt(); if (!e) return false; const t = Date.parse(e); return Number.isFinite(t) && Date.now() >= t; }); readonly isLoggedIn = computed(() => !!this._token() && !!this._me() && !this.isExpired()); /** * 写入登录态。 * * @param expiresAt 该 session 的过期时间(ISO)。**可选** —— * 手机验证码 / Token 直登拿不到时传空, * 退化为「不过期」,与改动前行为一致。 */ setSession(token: string, me: Me, expiresAt?: string | null): void { this._token.set(token); this._me.set(me); this._expiresAt.set(expiresAt ?? null); this.write(TOKEN_KEY, token); this.writeJson(ME_KEY, me); if (expiresAt) this.write(EXPIRES_KEY, expiresAt); else this.remove(EXPIRES_KEY); } /** 单独更新过期时间(登录后异步取到时补写) */ setExpiresAt(expiresAt: string | null): void { this._expiresAt.set(expiresAt ?? null); if (expiresAt) this.write(EXPIRES_KEY, expiresAt); else this.remove(EXPIRES_KEY); } setMe(me: Me): void { this._me.set(me); this.writeJson(ME_KEY, me); } /** * 启动时从服务端刷新身份(2026-11-05)。 * * ## 为什么需要 * * `me` 只在**登录那一刻**取一次,之后一直用 localStorage 的副本。 * 管理员在后台把某人提升/取消管理员后,该用户**不重新登录就永远看不到变化** —— * 表现为「明明加了管理员角色,页面还说没权限」(实测踩坑)。 * * ## 调用时机 * * 外壳启动时调一次(幂等、失败静默): * · 成功 → 用服务端最新 roles 覆盖本地 * · 失败(离线/过期)→ 保持本地副本,不打断使用 * * 🔴 只刷新身份,不动 token —— token 失效由 authGuard 统一处理。 */ async refreshMe(fetcher: (token: string) => Promise): Promise { const t = this._token(); if (!t) return; try { const latest = await fetcher(t); // 换号或退出后,旧身份刷新结果不得覆盖当前会话。 if (this._token() === t) this.setMe(latest); } catch { /* 离线 / token 过期:保留本地副本,不打断使用 */ } } /** 退出登录:清除本服务持有的全部键 */ logout(): void { this._token.set(null); this._me.set(null); this._expiresAt.set(null); try { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(ME_KEY); localStorage.removeItem(EXPIRES_KEY); } catch { /* 隐私模式下 localStorage 不可用,忽略 */ } } /** * 会话已失效(服务端 401)——清干净并通知全局跳登录页。 * * 与 `logout()` 的区别: * · `logout()` 是**用户主动**退出,页面自己导航 * · `expire()` 是**被动**失效,需要根组件统一接管跳转 * * 幂等:已经登出时只递增计数器,不重复清理。 */ expire(): void { this.logout(); this._expiredTick.update((n) => n + 1); } // ---------- 持久化(localStorage 不可用时静默降级为内存态) ---------- private remove(key: string): void { try { localStorage.removeItem(key); } catch { /* 隐私模式 / 配额:忽略 */ } } private read(key: string): string | null { try { return localStorage.getItem(key); } catch { return null; } } private readJson(key: string): T | null { const raw = this.read(key); if (!raw) return null; try { return JSON.parse(raw) as T; } catch { return null; } } private write(key: string, value: string): void { try { localStorage.setItem(key, value); } catch { /* 忽略 */ } } private writeJson(key: string, value: unknown): void { this.write(key, JSON.stringify(value)); } }