88 lines
2.3 KiB
TypeScript
88 lines
2.3 KiB
TypeScript
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 { App } from "antd";
|
|
import { createApiClient } from "../lib/api.js";
|
|
import { LoadingStack } from "../components/LoadingStack.js";
|
|
import { AdminErrorBoundary } from "../components/AdminErrorBoundary.js";
|
|
|
|
type SessionState = Omit<AdminSession, "authenticated">;
|
|
|
|
export function Root() {
|
|
const { message } = App.useApp();
|
|
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("登录状态已失效,请重新登录");
|
|
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 {
|
|
setSession(null);
|
|
}
|
|
};
|
|
|
|
if (loading) return <LoadingStack />;
|
|
if (!session)
|
|
return (
|
|
<Login
|
|
onLogin={(current) => {
|
|
setSession(current);
|
|
}}
|
|
/>
|
|
);
|
|
if (session.mustChangePassword)
|
|
return (
|
|
<ChangePassword
|
|
onComplete={async () => {
|
|
try {
|
|
setSession(await createApiClient().getAdminSession());
|
|
} catch {
|
|
setSession(null);
|
|
}
|
|
}}
|
|
/>
|
|
);
|
|
return (
|
|
<AdminErrorBoundary variant="page">
|
|
<AdminRouter>
|
|
<Dashboard
|
|
onLogout={logout}
|
|
role={session.role}
|
|
platformTemplateRole={session.platformTemplateRole}
|
|
/>
|
|
</AdminRouter>
|
|
</AdminErrorBoundary>
|
|
);
|
|
}
|