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

+1 -8
View File
@@ -12,7 +12,6 @@ import {
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import { createApiClient } from "../lib/api.js";
import { saveAdminSession } from "../lib/auth-storage.js";
import { BrandMark } from "../components/BrandMark.js";
import { StatusTag } from "../components/StatusTag.js";
import {
@@ -58,13 +57,7 @@ export function Dashboard({
});
const switchBrand = async (brandId: string) => {
try {
const result = await createApiClient().switchAdminBrand(brandId);
saveAdminSession({
token: result.token,
role: result.role,
platformTemplateRole,
mustChangePassword: false,
});
await createApiClient().switchAdminBrand(brandId);
window.location.reload();
} catch (error) {
message.error(error instanceof Error ? error.message : "品牌切换失败");
+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>
);
}
+1 -5
View File
@@ -2,7 +2,6 @@ import { CloudUploadOutlined, DeleteOutlined, PictureOutlined } from "@ant-desig
import { Alert, Button, Image, Popconfirm, Spin, Upload, message } from "antd";
import { useEffect, useMemo, useState } from "react";
import { apiBaseUrl, authenticatedFetch, createApiClient } from "../lib/api.js";
import { readAdminToken } from "../lib/auth-storage.js";
interface ImageUrlFieldProps {
id?: string;
@@ -57,10 +56,7 @@ export function ImageUrlField({ id, value, onChange, placeholder, scope }: Image
: presign.uploadUrl;
const response = await authenticatedFetch(uploadUrl, {
method: "PUT",
headers: {
"content-type": file.type,
...(isLocalUpload ? { authorization: `Bearer ${readAdminToken() ?? ""}` } : {}),
},
headers: { "content-type": file.type },
body: file,
});
if (!response.ok) throw new Error(`upload failed: ${response.status}`);
+2 -12
View File
@@ -1,28 +1,19 @@
import { useState } from "react";
import { createApiClient } from "../../lib/api.js";
import { markAdminPasswordChanged, saveAdminSession } from "../../lib/auth-storage.js";
import { BrandMark } from "../../components/BrandMark.js";
import { adminMessage as message } from "../../components/AdminMessage.js";
import { AdminButton } from "../../components/AdminButton.js";
import { AdminCard } from "../../components/AdminCard.js";
import { AdminForm, AdminInput } from "../../components/AdminForm.js";
import type { AdminLoginSession } from "@personal-brand/api-client";
export function Login({
onLogin,
}: {
onLogin: (session: {
role: string;
mustChangePassword: boolean;
platformTemplateRole: "none" | "template_admin";
}) => void;
}) {
export function Login({ onLogin }: { onLogin: (session: AdminLoginSession) => void }) {
const [form] = AdminForm.useForm();
const [loading, setLoading] = useState(false);
async function submit(values: { username: string; password: string }) {
setLoading(true);
try {
const result = await createApiClient().loginAdmin(values.username, values.password);
saveAdminSession(result);
onLogin(result);
} catch (error) {
message.error(error instanceof Error ? error.message : "登录失败");
@@ -79,7 +70,6 @@ export function ChangePassword({ onComplete }: { onComplete: () => void }) {
setLoading(true);
try {
await createApiClient().changeAdminPassword(values.currentPassword, values.newPassword);
markAdminPasswordChanged();
message.success("密码已更新");
onComplete();
} catch (error) {
+4 -11
View File
@@ -1,23 +1,16 @@
import { ApiClient } from "@personal-brand/api-client";
import { clearAdminSession, readAdminToken } from "./auth-storage.js";
export const apiBaseUrl = import.meta.env.VITE_API_BASE_URL ?? "/api";
export async function authenticatedFetch(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> {
const response = await fetch(input, init);
if (response.status === 401) {
clearAdminSession();
window.dispatchEvent(new Event("admin-auth-expired"));
}
if (response.status === 401) window.dispatchEvent(new Event("admin-auth-expired"));
return response;
}
export function createApiClient(): ApiClient {
const token = readAdminToken();
return new ApiClient({
baseUrl: apiBaseUrl,
...(token ? { token } : {}),
fetcher: authenticatedFetch,
});
return new ApiClient({ baseUrl: apiBaseUrl, fetcher: authenticatedFetch });
}
-48
View File
@@ -1,48 +0,0 @@
export type StoredAdminSession = {
token: string;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
};
const tokenKey = "adminToken";
const roleKey = "adminRole";
const platformRoleKey = "adminPlatformTemplateRole";
const mustChangePasswordKey = "adminMustChangePassword";
export function saveAdminSession(session: StoredAdminSession): void {
localStorage.setItem(tokenKey, session.token);
localStorage.setItem(roleKey, session.role);
localStorage.setItem(platformRoleKey, session.platformTemplateRole);
localStorage.setItem(mustChangePasswordKey, String(session.mustChangePassword));
}
export function readAdminToken(): string | null {
return localStorage.getItem(tokenKey);
}
export function readAdminSession(): {
loggedIn: boolean;
role: string;
platformTemplateRole: "none" | "template_admin";
mustChangePassword: boolean;
} {
return {
loggedIn: Boolean(localStorage.getItem(tokenKey)),
role: localStorage.getItem(roleKey) || "owner",
platformTemplateRole:
localStorage.getItem(platformRoleKey) === "template_admin" ? "template_admin" : "none",
mustChangePassword: localStorage.getItem(mustChangePasswordKey) === "true",
};
}
export function markAdminPasswordChanged(): void {
localStorage.setItem(mustChangePasswordKey, "false");
}
export function clearAdminSession(): void {
localStorage.removeItem(tokenKey);
localStorage.removeItem(roleKey);
localStorage.removeItem(platformRoleKey);
localStorage.removeItem(mustChangePasswordKey);
}