refactor: 收口 Admin 会话与授权边界

This commit is contained in:
que01 committed 2026-10-19 10:13:13 +08:00
1 parent 0788480ce3
commit 4ef4be2071
67 files changed
+1890 -392

No files matched your search

+39 -19
View File
@@ -1,52 +1,72 @@
import React, { useState } from "react";
import type { AdminSession } from "@personal-brand/api-client";
import { ChangePassword, Login } from "../features/auth/AuthPages.js";
import { Dashboard } from "./Dashboard.js";
import { AdminRouter } from "./AdminRouter.js";
import { adminMessage as message } from "../components/AdminMessage.js";
import { createApiClient } from "../lib/api.js";
import { clearAdminSession, readAdminSession } from "../lib/auth-storage.js";
import { LoadingStack } from "../components/LoadingStack.js";
type SessionState = Omit<AdminSession, "authenticated">;
export function Root() {
const initialSession = readAdminSession();
const [loggedIn, setLoggedIn] = useState(initialSession.loggedIn);
const [role, setRole] = useState(initialSession.role);
const [platformTemplateRole, setPlatformTemplateRole] = useState(
initialSession.platformTemplateRole,
);
const [mustChangePassword, setMustChangePassword] = useState(initialSession.mustChangePassword);
const [session, setSession] = useState<SessionState | null>(null);
const [loading, setLoading] = useState(true);
React.useEffect(() => {
let active = true;
createApiClient()
.getAdminSession()
.then((current) => {
if (active) setSession(current);
})
.catch(() => {
if (active) setSession(null);
})
.finally(() => {
if (active) setLoading(false);
});
return () => {
active = false;
};
}, []);
React.useEffect(() => {
const expire = () => {
message.warning("登录状态已失效,请重新登录");
setLoggedIn(false);
setSession(null);
};
window.addEventListener("admin-auth-expired", expire);
return () => window.removeEventListener("admin-auth-expired", expire);
}, []);
const logout = async () => {
try {
await createApiClient().logoutAdmin();
} catch {
message.warning("已退出本地会话;服务端撤销请求未完成");
} finally {
clearAdminSession();
setLoggedIn(false);
setSession(null);
}
};
if (!loggedIn)
if (loading) return <LoadingStack />;
if (!session)
return (
<Login
onLogin={(session) => {
setRole(session.role);
setPlatformTemplateRole(session.platformTemplateRole);
setMustChangePassword(session.mustChangePassword);
setLoggedIn(true);
onLogin={(current) => {
setSession(current);
}}
/>
);
if (mustChangePassword) return <ChangePassword onComplete={() => setMustChangePassword(false)} />;
if (session.mustChangePassword) return <ChangePassword onComplete={() => setSession(null)} />;
return (
<AdminRouter>
<Dashboard onLogout={logout} role={role} platformTemplateRole={platformTemplateRole} />
<Dashboard
onLogout={logout}
role={session.role}
platformTemplateRole={session.platformTemplateRole}
/>
</AdminRouter>
);
}