/** * 会话装载:GET /database/api/me 一次,结果进 `me` store。 * 老师端与管理后台共用 —— 两处的区别只是拿到 me 之后怎么用 * (老师端未登录显示登录视图;管理后台未登录跳 /database/admin, * 非 isWebsiteAdmin 显示无权提示)。 */ import { get } from "svelte/store"; import { api, UnauthenticatedError } from "./api.js"; import { me, authChecked } from "./stores.js"; import type { MeResponse } from "./types.js"; /** 幂等:已检查过就不再打请求(路由间切换不重复拉取)。 */ export async function loadSession(force = false): Promise { if (get(authChecked) && !force) return; try { me.set(await api("/database/api/me")); } catch (e) { if (!(e instanceof UnauthenticatedError)) console.error(e); me.set(null); } finally { authChecked.set(true); } } /** 退出登录:清后端 cookie 再清前端 store。 */ export async function logout(): Promise { try { await fetch("/auth/logout", { method: "POST", credentials: "same-origin" }); } catch { /* 网络失败也照样清前端状态 */ } me.set(null); }