Compare commits

...
Author SHA1 Message Date
jiang e3ab82f6df fix(3d): unify station area mode labels
Generic Container CI/CD / test-build-publish (push) Successful in 1m0s
Frontend CI/CD v2 / build-test-publish-and-deploy (push) Successful in 1m0s
2026-11-04 14:12:49 +08:00
jiang 5a0bb6864a fix(auth): align restricted header and logout state 2026-11-04 14:12:44 +08:00
jiang 80f05e481b fix(auth): keep logout and project recovery on access denial
Generic Container CI/CD / test-build-publish (push) Successful in 1m3s
Frontend CI/CD v2 / build-test-publish-and-deploy (push) Successful in 1m3s
2026-11-04 13:51:05 +08:00
jiang 6ff5322353 fix(api): align generated server contract
Generic Container CI/CD / test-build-publish (push) Successful in 1m4s
Frontend CI/CD v2 / build-test-publish-and-deploy (push) Successful in 1m4s
2026-11-04 13:38:21 +08:00
jiang ca1c41aa9d feat(admin): sync and authorize Keycloak users
Generic Container CI/CD / test-build-publish (push) Successful in 1m5s
Frontend CI/CD v2 / build-test-publish-and-deploy (push) Successful in 1m5s
2026-11-04 13:35:29 +08:00
17 changed files with 848 additions and 86 deletions
+1 -1
View File
@@ -7,7 +7,7 @@
},
"server": {
"file": "server-v1.openapi.json",
"sha256": "b565d841061c9091f48ff3118bcc0cbb1b918b0cb8c2316d177570e8b2d8ba29"
"sha256": "1edfd78405cfe2a50022afe70a4c4f32caa4e98e3b5b54b40841d532058f2fd6"
}
}
}
+156
View File
@@ -1201,6 +1201,59 @@
"type": "string"
},
"JsonValue": {},
"KeycloakUserSyncIssue": {
"properties": {
"reason": {
"title": "Reason",
"type": "string"
},
"username": {
"title": "Username",
"type": "string"
}
},
"required": [
"username",
"reason"
],
"title": "KeycloakUserSyncIssue",
"type": "object"
},
"KeycloakUserSyncResponse": {
"properties": {
"created": {
"title": "Created",
"type": "integer"
},
"issues": {
"items": {
"$ref": "#/components/schemas/KeycloakUserSyncIssue"
},
"title": "Issues",
"type": "array"
},
"scanned": {
"title": "Scanned",
"type": "integer"
},
"skipped": {
"title": "Skipped",
"type": "integer"
},
"updated": {
"title": "Updated",
"type": "integer"
}
},
"required": [
"scanned",
"created",
"updated",
"skipped"
],
"title": "KeycloakUserSyncResponse",
"type": "object"
},
"LeakageIdentifyRequestRest": {
"properties": {
"dma_count": {
@@ -3201,6 +3254,92 @@
]
}
},
"/api/v1/admin/keycloak-user-syncs": {
"post": {
"operationId": "post_admin_keycloak_user_syncs",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/KeycloakUserSyncResponse"
}
}
},
"description": "Successful Response"
},
"401": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Authentication required"
},
"403": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Insufficient permission"
},
"404": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Resource not found"
},
"409": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Resource conflict"
},
"422": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Validation error"
},
"503": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
},
"description": "Dependency unavailable"
}
},
"security": [
{
"OAuth2PasswordBearer": []
}
],
"summary": "Sync Keycloak User Directory",
"tags": [
"Metadata Admin"
]
}
},
"/api/v1/admin/project-provisions": {
"post": {
"operationId": "post_admin_project_provisions",
@@ -35969,6 +36108,23 @@
"type": "array"
}
},
{
"description": "事故要素类型;auto优先管段再节点;分析同名节点须指定node,纯管段分析可指定link",
"in": "query",
"name": "accident_element_type",
"required": false,
"schema": {
"default": "auto",
"description": "事故要素类型;auto优先管段再节点;分析同名节点须指定node,纯管段分析可指定link",
"enum": [
"auto",
"link",
"node"
],
"title": "Accident Element Type",
"type": "string"
}
},
{
"in": "header",
"name": "X-Project-Id",
+73
View File
@@ -15,3 +15,76 @@ test("已登录管理员可以打开审计日志页面", async ({ page }) => {
await expect(page.getByText("系统管理员权限已验证")).toBeVisible();
await expect(page.getByRole("heading", { name: "查询结果" })).toBeVisible();
});
test("已认证但未授权的账号会看到明确说明", async ({ page }) => {
await page.addInitScript(() => window.localStorage.clear());
await page.route("**/api/v1/access-context", (route) =>
route.fulfill({
status: 403,
contentType: "application/json",
body: JSON.stringify({ detail: "User authorization pending" }),
}),
);
await page.goto("/");
await expect(page.getByText("账号尚未获得访问权限")).toBeVisible();
await expect(
page.getByText("身份认证已成功,但当前账号尚未由系统管理员启用"),
).toBeVisible();
const accountMenu = page.getByRole("button", {
name: "E2E 测试用户 账号菜单",
});
await expect(accountMenu).toBeVisible();
await accountMenu.click();
await expect(page.getByRole("menuitem", { name: "登出" })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "切换项目" })).toHaveCount(0);
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByText("账号尚未获得访问权限")).toBeVisible();
await expect(accountMenu).toBeVisible();
});
test("无权访问项目时可以在窄屏切换项目", async ({ page }) => {
await page.route("**/api/v1/access-context", (route) =>
route.fulfill({
status: 403,
contentType: "application/json",
body: JSON.stringify({ detail: "No access to project" }),
}),
);
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/");
await expect(page.getByText("无权访问当前项目")).toBeVisible();
await page
.getByRole("button", { name: "E2E 测试用户 账号菜单" })
.click();
await page.getByRole("menuitem", { name: "切换项目" }).click();
const projectDialog = page.getByRole("dialog");
await expect(projectDialog).toBeVisible();
const bounds = await projectDialog.boundingBox();
expect(bounds).not.toBeNull();
expect(bounds!.x).toBeGreaterThanOrEqual(0);
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390);
});
test("系统管理员可以手动同步 Keycloak 用户目录", async ({ page }) => {
await page.goto("/system-admin");
await page.getByRole("tab", { name: "系统用户" }).click();
await page.getByRole("button", { name: "同步 Keycloak 用户" }).click();
await expect(page.getByRole("button", { name: "正在同步" })).toBeDisabled();
await expect(
page.getByText("已扫描 3 个 Keycloak 身份,新增 1 个,更新 1 个,跳过 1 个。"),
).toBeVisible();
await expect(page.getByText("跳过项包括服务账号、缺少邮箱或身份冲突")).toBeVisible();
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByRole("button", { name: "同步 Keycloak 用户" })).toBeVisible();
await expect(page.getByRole("button", { name: "刷新", exact: true })).toBeVisible();
});
+18 -1
View File
@@ -50,10 +50,27 @@ export const mockBackend = async (page: Page) => {
return json(route, { count: 0 });
}
if (
url.pathname === "/api/v1/admin/keycloak-user-syncs" &&
route.request().method() === "POST"
) {
await new Promise((resolve) => setTimeout(resolve, 150));
return json(route, {
scanned: 3,
created: 1,
updated: 1,
skipped: 1,
issues: [{ username: "no-email", reason: "missing_email" }],
});
}
if (
url.pathname === "/api/v1/audit-logs" ||
url.pathname === "/api/v1/admin/users" ||
url.pathname === "/api/v1/admin/projects"
url.pathname === "/api/v1/admin/projects" ||
/^\/api\/v1\/admin\/projects\/[^/]+\/(members|databases)$/.test(
url.pathname,
)
) {
return json(route, []);
}
+78 -2
View File
@@ -18,6 +18,8 @@ let mockSessionState: {
},
status: "authenticated",
};
let mockPathname = "/network-simulation";
let mockProjectProviderBlocks = false;
jest.mock("next-auth/react", () => ({
SessionProvider: ({ children }: { children: ReactNode }) => children,
@@ -26,7 +28,7 @@ jest.mock("next-auth/react", () => ({
}));
jest.mock("next/navigation", () => ({
usePathname: () => "/network-simulation",
usePathname: () => mockPathname,
}));
jest.mock("@refinedev/core", () => ({
@@ -43,6 +45,11 @@ jest.mock("@refinedev/mui", () => ({
}));
jest.mock("@refinedev/nextjs-router", () => ({}));
jest.mock("@/components/header", () => ({
Header: ({ accessMode }: { accessMode: string }) => (
<div data-testid="access-header">{accessMode}</div>
),
}));
jest.mock("@providers/data-provider", () => ({ dataProvider: {} }));
jest.mock("@/providers/notification-provider/useAppNotificationProvider", () => ({
useAppNotificationProvider: {},
@@ -51,7 +58,8 @@ jest.mock("@contexts/color-mode", () => ({
ColorModeContextProvider: ({ children }: { children: ReactNode }) => children,
}));
jest.mock("@/contexts/ProjectContext", () => ({
ProjectProvider: ({ children }: { children: ReactNode }) => children,
ProjectProvider: ({ children }: { children: ReactNode }) =>
mockProjectProviderBlocks ? <div>请选择项目环境</div> : children,
}));
jest.mock("@/lib/authToken", () => ({
getAccessToken: jest.fn().mockResolvedValue("expired-access-token"),
@@ -62,6 +70,8 @@ describe("RefineContext access authentication", () => {
const originalRequest = global.Request;
beforeEach(() => {
mockPathname = "/network-simulation";
mockProjectProviderBlocks = false;
mockSessionState = {
data: {
accessToken: "expired-access-token",
@@ -115,6 +125,54 @@ describe("RefineContext access authentication", () => {
});
});
it("shows an authorization message when access-context rejects the account", async () => {
mockProjectProviderBlocks = true;
global.fetch = jest.fn().mockResolvedValue({
ok: false,
status: 403,
headers: new Headers(),
json: async () => ({ detail: "User authorization pending" }),
} as Response);
render(
<App>
<div>应用内容</div>
</App>,
);
expect(
await screen.findByText("账号尚未获得访问权限"),
).toBeInTheDocument();
expect(screen.getByTestId("access-header")).toHaveTextContent("account");
expect(screen.queryByText("应用内容")).not.toBeInTheDocument();
expect(useAuthStore.getState()).toMatchObject({
sessionExpired: false,
sessionExpiryReason: null,
});
});
it("keeps project recovery available when the selected project is denied", async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: false,
status: 403,
headers: new Headers(),
json: async () => ({ detail: "No access to project" }),
} as Response);
render(
<App>
<div>应用内容</div>
</App>,
);
expect(await screen.findByText("无权访问当前项目")).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "切换项目" }),
).not.toBeInTheDocument();
expect(screen.getByTestId("access-header")).toHaveTextContent("project");
expect(screen.queryByText("应用内容")).not.toBeInTheDocument();
});
it("prioritizes an unauthenticated session over route permissions", async () => {
mockSessionState = { data: null, status: "unauthenticated" };
@@ -134,4 +192,22 @@ describe("RefineContext access authentication", () => {
});
});
});
it("does not treat an intentional logout landing on login as session expiry", async () => {
mockPathname = "/login";
mockSessionState = { data: null, status: "unauthenticated" };
render(
<App>
<div>登录页面</div>
</App>,
);
await waitFor(() => {
expect(useAuthStore.getState()).toMatchObject({
sessionExpired: false,
sessionExpiryReason: null,
});
});
});
});
+77 -44
View File
@@ -9,7 +9,7 @@ import { RefineKbar, RefineKbarProvider } from "@refinedev/kbar";
import { RefineSnackbarProvider } from "@refinedev/mui";
import { SessionProvider, signIn, useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import React, { useEffect } from "react";
import React, { useEffect, useState } from "react";
import routerProvider from "@refinedev/nextjs-router";
import { NavigationLink } from "@components/loading/NavigationLink";
@@ -75,6 +75,9 @@ export const App = (props: React.PropsWithChildren<AppProps>) => {
const setAccessContext = useAccessStore((state) => state.setContext);
const setAccessLoading = useAccessStore((state) => state.setLoading);
const resetAccess = useAccessStore((state) => state.reset);
const [accessDeniedReason, setAccessDeniedReason] = useState<
"account" | "project" | null
>(null);
const can = (permission: string) => permissions.includes(permission);
useEffect(() => {
@@ -93,31 +96,53 @@ export const App = (props: React.PropsWithChildren<AppProps>) => {
return;
}
if (status === "unauthenticated") {
if (to === "/login") {
clearSessionExpired();
return;
}
markSessionExpired("unauthorized");
return;
}
if (status === "authenticated") {
clearSessionExpired();
}
}, [clearSessionExpired, data?.error, markSessionExpired, status]);
}, [clearSessionExpired, data?.error, markSessionExpired, status, to]);
useEffect(() => {
if (status !== "authenticated") {
setAccessDeniedReason(null);
resetAccess();
return;
}
let cancelled = false;
setAccessDeniedReason(null);
setAccessLoading(true);
apiFetch(`${config.BACKEND_URL}/api/v1/access-context`, {
projectHeaderMode: currentProjectId ? "include" : "omit",
})
.then(async (response) => {
if (cancelled) return;
if (response.status === 403) {
let detail = "";
try {
const payload = await response.json();
detail = typeof payload?.detail === "string" ? payload.detail : "";
} catch {
// Treat an unparseable 403 as a project access failure so the user
// keeps a recovery path instead of being trapped in the account shell.
}
setAccessDeniedReason(
detail === "User authorization pending" ? "account" : "project",
);
resetAccess();
return;
}
if (!response.ok) {
resetAccess();
return;
}
setAccessDeniedReason(null);
setAccessContext(await response.json());
})
.catch(() => {
@@ -157,6 +182,28 @@ export const App = (props: React.PropsWithChildren<AppProps>) => {
return <span>loading...</span>;
}
const handleLogout = () =>
completeLogout({
reportAudit: () =>
reportLogoutAudit({
endpoint: `${config.BACKEND_URL}/api/v1/audit-events`,
accessToken:
typeof data?.accessToken === "string"
? data.accessToken
: useAuthStore.getState().accessToken,
}),
clearLocalState: () => {
const authStore = useAuthStore.getState();
authStore.setAccessToken(null);
authStore.clearSessionExpired();
if (data?.user?.id) {
sessionStorage.removeItem(`tjwater-login-audit:${data.user.id}`);
}
clearSessionRecoveryDrafts();
},
navigate: (path) => window.location.assign(path),
});
const authProvider: AuthProvider = {
login: async () => {
signIn("keycloak", {
@@ -165,24 +212,7 @@ export const App = (props: React.PropsWithChildren<AppProps>) => {
});
return { success: true };
},
logout: () =>
completeLogout({
reportAudit: () =>
reportLogoutAudit({
endpoint: `${config.BACKEND_URL}/api/v1/audit-events`,
accessToken:
typeof data?.accessToken === "string"
? data.accessToken
: useAuthStore.getState().accessToken,
}),
clearLocalState: () => {
if (data?.user?.id) {
sessionStorage.removeItem(`tjwater-login-audit:${data.user.id}`);
}
clearSessionRecoveryDrafts();
},
navigate: (path) => window.location.assign(path),
}),
logout: handleLogout,
onError: async (error) => {
return { error };
},
@@ -375,31 +405,34 @@ export const App = (props: React.PropsWithChildren<AppProps>) => {
];
return (
<ProjectProvider>
<RefineKbarProvider>
<ColorModeContextProvider defaultMode={props.defaultMode}>
<RefineSnackbarProvider>
<Refine
routerProvider={appRouterProvider}
dataProvider={dataProvider}
notificationProvider={useAppNotificationProvider}
authProvider={authProvider}
accessControlProvider={accessControlProvider}
resources={resources}
options={{
syncWithLocation: true,
warnWhenUnsavedChanges: true,
}}
<RefineKbarProvider>
<ColorModeContextProvider defaultMode={props.defaultMode}>
<RefineSnackbarProvider>
<Refine
routerProvider={appRouterProvider}
dataProvider={dataProvider}
notificationProvider={useAppNotificationProvider}
authProvider={authProvider}
accessControlProvider={accessControlProvider}
resources={resources}
options={{
syncWithLocation: true,
warnWhenUnsavedChanges: true,
}}
>
<SessionExpiryDialog expiresAt={data?.sessionExpiresAt} />
<RoutePermissionGuard
authenticated={status === "authenticated"}
accessDeniedReason={accessDeniedReason}
>
<SessionExpiryDialog expiresAt={data?.sessionExpiresAt} />
<RoutePermissionGuard authenticated={status === "authenticated"}>
<ProjectProvider>
{props.children}
</RoutePermissionGuard>
<RefineKbar />
</Refine>
</RefineSnackbarProvider>
</ColorModeContextProvider>
</RefineKbarProvider>
</ProjectProvider>
</ProjectProvider>
</RoutePermissionGuard>
<RefineKbar />
</Refine>
</RefineSnackbarProvider>
</ColorModeContextProvider>
</RefineKbarProvider>
);
};
@@ -1,5 +1,36 @@
import authOptions from "./options";
describe("Keycloak profile mapping", () => {
const mapProfile = authOptions.providers[0].profile as (profile: {
sub: string;
preferred_username: string;
name?: string;
email?: string;
picture?: string;
}) => { image?: string | null };
it("uses the Keycloak picture instead of a shared local avatar", () => {
expect(
mapProfile({
sub: "user-1",
preferred_username: "zjb",
picture: "https://keycloak.example/avatar/zjb.png",
}),
).toMatchObject({
image: "https://keycloak.example/avatar/zjb.png",
});
});
it("leaves the image empty when Keycloak has no picture", () => {
const profile = mapProfile({
sub: "user-1",
preferred_username: "zjb",
});
expect(profile.image).toBeUndefined();
});
});
describe("NextAuth access token refresh", () => {
it("forces a Keycloak refresh for an agent credential request", async () => {
const previousEnv = {
+5 -2
View File
@@ -1,7 +1,6 @@
import { NextAuthOptions } from "next-auth";
import { JWT } from "next-auth/jwt";
import KeycloakProvider from "next-auth/providers/keycloak";
import Avatar from "@assets/avatar/avatar-small.jpeg";
const SESSION_MAX_AGE_SECONDS = 12 * 60 * 60;
const ACCESS_TOKEN_REFRESH_SKEW_MS = 30_000;
@@ -86,12 +85,16 @@ const authOptions: NextAuthOptions = {
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET ?? "",
issuer: process.env.KEYCLOAK_ISSUER ?? "",
profile(profile) {
const picture =
typeof (profile as { picture?: unknown }).picture === "string"
? String((profile as { picture: string }).picture).trim()
: "";
return {
id: profile.sub,
username: profile.preferred_username,
name: profile.name ?? profile.preferred_username,
email: profile.email,
image: Avatar.src,
image: picture || null,
};
},
}),
@@ -0,0 +1,87 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { apiFetch } from "@/lib/apiFetch";
import { SystemAdminPanel } from "./SystemAdminPanel";
const openNotification = jest.fn();
jest.mock("@refinedev/core", () => ({
useNotification: () => ({ open: openNotification }),
}));
jest.mock("@config/config", () => ({
config: { BACKEND_URL: "https://server.example.com" },
}));
jest.mock("@/lib/apiFetch", () => ({
apiFetch: jest.fn(),
}));
jest.mock("@/lib/sessionRecoveryDraft", () => ({
useSessionRecoveryDraft: jest.fn(),
}));
jest.mock("@/store/projectStore", () => ({
useProjectStore: (selector: (state: { currentProjectId: null }) => unknown) =>
selector({ currentProjectId: null }),
}));
const jsonResponse = (body: unknown) =>
({
ok: true,
status: 200,
json: async () => body,
text: async () => JSON.stringify(body),
}) as Response;
describe("SystemAdminPanel Keycloak synchronization", () => {
beforeEach(() => {
jest.clearAllMocks();
(apiFetch as jest.Mock).mockImplementation((input: string) => {
if (input.endsWith("/api/v1/admin/users/me")) {
return Promise.resolve(
jsonResponse({
id: "admin-id",
keycloak_id: "admin-keycloak-id",
username: "admin",
email: "admin@example.com",
role: "admin",
is_active: true,
is_superuser: true,
}),
);
}
if (input.endsWith("/api/v1/admin/keycloak-user-syncs")) {
return Promise.resolve(
jsonResponse({
scanned: 3,
created: 1,
updated: 1,
skipped: 1,
issues: [{ username: "no-email", reason: "missing_email" }],
}),
);
}
return Promise.resolve(jsonResponse([]));
});
});
it("syncs the Keycloak directory and shows the result", async () => {
render(<SystemAdminPanel />);
fireEvent.click(await screen.findByRole("tab", { name: "系统用户" }));
fireEvent.click(
screen.getByRole("button", { name: "同步 Keycloak 用户" }),
);
await waitFor(() => {
expect(apiFetch).toHaveBeenCalledWith(
"https://server.example.com/api/v1/admin/keycloak-user-syncs",
expect.objectContaining({ method: "POST" }),
);
});
expect(await screen.findByRole("alert")).toHaveTextContent(
"已扫描 3 个 Keycloak 身份,新增 1 个,更新 1 个,跳过 1 个。",
);
});
});
+77 -4
View File
@@ -53,6 +53,7 @@ import {
Save as SaveIcon,
Security as SecurityIcon,
Storage as StorageIcon,
Sync as SyncIcon,
} from "@mui/icons-material";
import { useNotification } from "@refinedev/core";
import { config } from "@config/config";
@@ -70,6 +71,17 @@ type MetadataUser = {
is_superuser: boolean;
};
type KeycloakUserSyncResult = {
scanned: number;
created: number;
updated: number;
skipped: number;
issues: Array<{
username: string;
reason: "missing_email" | "service_account" | "identity_conflict" | string;
}>;
};
type ProjectMember = {
id: string;
user_id: string;
@@ -469,6 +481,9 @@ export const SystemAdminPanel = () => {
const [adminChecked, setAdminChecked] = useState(false);
const [isAuthorized, setIsAuthorized] = useState(false);
const [metadataConfigAvailable, setMetadataConfigAvailable] = useState(true);
const [syncingKeycloakUsers, setSyncingKeycloakUsers] = useState(false);
const [keycloakSyncResult, setKeycloakSyncResult] =
useState<KeycloakUserSyncResult | null>(null);
const [projectId, setProjectId] = useState(currentProjectId ?? "");
const [memberForm, setMemberForm] = useState({
user_id: "",
@@ -564,6 +579,33 @@ export const SystemAdminPanel = () => {
setUsers(await response.json());
}, []);
const syncKeycloakUsers = useCallback(async () => {
if (syncingKeycloakUsers) return;
setSyncingKeycloakUsers(true);
try {
const response = await apiFetch(
`${config.BACKEND_URL}/api/v1/admin/keycloak-user-syncs`,
{
method: "POST",
projectHeaderMode: "omit",
},
);
if (!response.ok) {
throw new Error(await readErrorText(response));
}
const result = (await response.json()) as KeycloakUserSyncResult;
setKeycloakSyncResult(result);
await loadUsers();
notifySuccess(
`Keycloak 用户同步完成:新增 ${result.created},更新 ${result.updated},跳过 ${result.skipped}`,
);
} catch (error) {
notifyError(error instanceof Error ? error.message : String(error));
} finally {
setSyncingKeycloakUsers(false);
}
}, [loadUsers, notifyError, notifySuccess, syncingKeycloakUsers]);
const applyProjectForm = useCallback((project: AdminProject | null) => {
if (!project) {
setProjectForm(defaultProjectForm);
@@ -1238,13 +1280,44 @@ export const SystemAdminPanel = () => {
<Stack spacing={2}>
<SectionHeader
title="系统用户"
description="Keycloak 信息只读展示;这里维护系统角色和启用状态。超级管理员由后台初始化或受控脚本设置,不在页面修改。"
description="从 Keycloak 同步身份后,在这里维护系统角色和启用状态。新用户默认停用,项目权限仍需单独配置。"
action={
<Button startIcon={<RefreshIcon />} variant="outlined" onClick={loadUsers}>
刷新
</Button>
<Stack direction="row" spacing={1} useFlexGap flexWrap="wrap">
<Button
startIcon={
syncingKeycloakUsers ? (
<CircularProgress color="inherit" size={16} />
) : (
<SyncIcon />
)
}
variant="contained"
disabled={syncingKeycloakUsers}
onClick={() => void syncKeycloakUsers()}
>
{syncingKeycloakUsers ? "正在同步" : "同步 Keycloak 用户"}
</Button>
<Button
startIcon={<RefreshIcon />}
variant="outlined"
disabled={syncingKeycloakUsers}
onClick={() => void loadUsers()}
>
刷新
</Button>
</Stack>
}
/>
{keycloakSyncResult && (
<Alert
severity={keycloakSyncResult.skipped > 0 ? "warning" : "success"}
sx={{ borderRadius: 2 }}
>
{`已扫描 ${keycloakSyncResult.scanned} 个 Keycloak 身份,新增 ${keycloakSyncResult.created} 个,更新 ${keycloakSyncResult.updated} 个,跳过 ${keycloakSyncResult.skipped} 个。`}
{keycloakSyncResult.skipped > 0 &&
" 跳过项包括服务账号、缺少邮箱或身份冲突,请检查 Keycloak 用户资料。"}
</Alert>
)}
<TableContainer component={Paper} variant="outlined" sx={{ borderRadius: 2 }}>
<Table size="small" sx={tableSx}>
<TableHead>
@@ -8,6 +8,12 @@ jest.mock("next/navigation", () => ({
usePathname: () => "/network-simulation",
}));
jest.mock("@/components/header", () => ({
Header: ({ accessMode }: { accessMode: string }) => (
<div data-testid="access-header">{accessMode}</div>
),
}));
describe("RoutePermissionGuard", () => {
beforeEach(() => {
useAccessStore.setState({
@@ -52,6 +58,34 @@ describe("RoutePermissionGuard", () => {
expect(screen.getByText(/simulation\.view/)).toBeInTheDocument();
});
it("keeps a minimal identity header and logout action for pending accounts", () => {
render(
<RoutePermissionGuard
authenticated
accessDeniedReason="account"
>
<div>受保护内容</div>
</RoutePermissionGuard>,
);
expect(screen.getByTestId("access-header")).toHaveTextContent("account");
expect(screen.queryByText("受保护内容")).not.toBeInTheDocument();
});
it("keeps project recovery available when only the selected project is denied", () => {
render(
<RoutePermissionGuard
authenticated
accessDeniedReason="project"
>
<div>受保护内容</div>
</RoutePermissionGuard>,
);
expect(screen.getByText("无权访问当前项目")).toBeInTheDocument();
expect(screen.getByTestId("access-header")).toHaveTextContent("project");
});
it("checks authentication before the expired state effect runs", () => {
render(
<RoutePermissionGuard authenticated={false}>
+43 -1
View File
@@ -1,10 +1,17 @@
"use client";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";
import {
Alert,
Box,
CircularProgress,
Stack,
Typography,
} from "@mui/material";
import { usePathname } from "next/navigation";
import type { ReactNode } from "react";
import { Header } from "@/components/header";
import { permissionForPath } from "@/lib/permissions";
import { useAccessStore } from "@/store/accessStore";
import { useAuthStore } from "@/store/authStore";
@@ -12,9 +19,11 @@ import { useAuthStore } from "@/store/authStore";
export const RoutePermissionGuard = ({
children,
authenticated,
accessDeniedReason = null,
}: {
children: ReactNode;
authenticated: boolean;
accessDeniedReason?: "account" | "project" | null;
}) => {
const pathname = usePathname();
const permissions = useAccessStore((state) => state.permissions);
@@ -37,6 +46,39 @@ export const RoutePermissionGuard = ({
);
}
if (accessDeniedReason) {
const accountPending = accessDeniedReason === "account";
return (
<Box sx={{ minHeight: "100vh", bgcolor: "background.default" }}>
<Header accessMode={accessDeniedReason} />
<Box
component="main"
sx={{
width: "100%",
maxWidth: 840,
mx: "auto",
px: { xs: 2, sm: 3 },
py: { xs: 4, md: 8 },
}}
>
<Alert severity="warning" icon={<LockOutlinedIcon />}>
<Stack spacing={0.5}>
<Typography fontWeight={700}>
{accountPending ? "账号尚未获得访问权限" : "无权访问当前项目"}
</Typography>
<Typography variant="body2">
{accountPending
? "身份认证已成功,但当前账号尚未由系统管理员启用。请联系系统管理员完成授权后重试。"
: "当前账号无法访问所选项目。请选择其他已授权项目,或联系系统管理员调整项目权限。"}
</Typography>
</Stack>
</Alert>
</Box>
</Box>
);
}
if (requiredPermission && loading) {
return (
<Box sx={{ minHeight: 320, display: "grid", placeItems: "center" }}>
+48 -27
View File
@@ -3,6 +3,7 @@
import { ColorModeContext } from "@contexts/color-mode";
import DarkModeOutlined from "@mui/icons-material/DarkModeOutlined";
import LightModeOutlined from "@mui/icons-material/LightModeOutlined";
import { FiUser } from "react-icons/fi";
import { IoChatbubbleEllipsesOutline } from "react-icons/io5";
import Logout from "@mui/icons-material/Logout";
import SwapHoriz from "@mui/icons-material/SwapHoriz";
@@ -37,8 +38,13 @@ type IUser = {
avatar?: string;
};
export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
type HeaderProps = RefineThemedLayoutHeaderProps & {
accessMode?: "default" | "account" | "project";
};
export const Header: React.FC<HeaderProps> = ({
sticky = true,
accessMode = "default",
}) => {
const { mode, setMode } = useContext(ColorModeContext);
const { mutate: logout } = useLogout();
@@ -51,6 +57,7 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
);
const { data: user } = useGetIdentity<IUser>();
const restricted = accessMode !== "default";
const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
@@ -92,7 +99,7 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
justifyContent="flex-end"
alignItems="center"
>
<HamburgerMenu />
{!restricted && <HamburgerMenu />}
<Stack
direction="row"
width="100%"
@@ -110,20 +117,26 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
{(user?.avatar || user?.name) && (
<>
<IconButton
color="inherit"
onClick={() => setShowChatbox(true)}
sx={{ mr: 1 }}
>
<IoChatbubbleEllipsesOutline />
</IconButton>
{!restricted && (
<IconButton
color="inherit"
onClick={() => setShowChatbox(true)}
sx={{ mr: 1 }}
>
<IoChatbubbleEllipsesOutline />
</IconButton>
)}
<ButtonBase
aria-label={
user?.name ? `${user.name} 账号菜单` : "账号菜单"
}
onClick={handleMenuOpen}
sx={{
borderRadius: "30px",
padding: "6px 12px",
marginLeft: "8px",
transition: "all 0.3s ease",
transition:
"background-color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease, transform 0.3s ease",
border: "1px solid transparent",
"&:hover": {
backgroundColor:
@@ -182,7 +195,9 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
borderColor: "primary.main",
},
}}
/>
>
{!user?.avatar && <FiUser aria-hidden="true" />}
</Avatar>
</Stack>
</ButtonBase>
<Menu
@@ -208,13 +223,15 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
},
}}
>
<MenuItem onClick={handleSwitchProjectClick}>
<ListItemIcon>
<SwapHoriz fontSize="small" />
</ListItemIcon>
<ListItemText>切换项目</ListItemText>
</MenuItem>
<Divider />
{accessMode !== "account" && (
<MenuItem onClick={handleSwitchProjectClick}>
<ListItemIcon>
<SwapHoriz fontSize="small" />
</ListItemIcon>
<ListItemText>切换项目</ListItemText>
</MenuItem>
)}
{accessMode !== "account" && <Divider />}
<MenuItem onClick={() => logout()}>
<ListItemIcon>
<Logout fontSize="small" />
@@ -222,17 +239,21 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
<ListItemText>登出</ListItemText>
</MenuItem>
</Menu>
<ProjectSelector
open={showProjectSelector}
onSelect={handleProjectSelect}
onClose={() => setShowProjectSelector(false)}
/>
{accessMode !== "account" && (
<ProjectSelector
open={showProjectSelector}
onSelect={handleProjectSelect}
onClose={() => setShowProjectSelector(false)}
/>
)}
</>
)}
<GlobalChatbox
open={showChatbox}
onClose={() => setShowChatbox(false)}
/>
{!restricted && (
<GlobalChatbox
open={showChatbox}
onClose={() => setShowChatbox(false)}
/>
)}
</Stack>
</Stack>
</Toolbar>
+5 -2
View File
@@ -132,8 +132,11 @@ export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
paper: {
sx: {
borderRadius: 2,
padding: 2,
minWidth: 400,
boxSizing: "border-box",
margin: { xs: 2, sm: 4 },
padding: { xs: 1.5, sm: 2 },
width: { xs: "calc(100vw - 32px)", sm: 400 },
maxWidth: "calc(100vw - 32px)",
background: "rgba(255, 255, 255, 0.95)",
backdropFilter: "blur(10px)",
position: "relative",
@@ -110,7 +110,7 @@ describe("ThreeDimensionalControls", () => {
/>,
);
fireEvent.click(screen.getByRole("button", { name: "站房精细版" }));
fireEvent.click(screen.getByRole("button", { name: "站区精细版" }));
expect(onCommand).toHaveBeenCalledWith({ name: "set-mode", mode: "detail" });
fireEvent.change(screen.getByRole("slider", { name: "建筑背景透明度 60%" }), {
target: { value: "0.35" },
@@ -35,7 +35,7 @@ const sceneModes: Array<{ mode: SceneMode; label: string }> = [
{ mode: "network", label: "供水管网" },
{ mode: "hydraulic", label: "泵组与管网" },
{ mode: "map", label: "站区轻量版" },
{ mode: "detail", label: "站房精细版" },
{ mode: "detail", label: "站区精细版" },
{ mode: "pump", label: "CAD 泵房参考" },
{ mode: "meters", label: "设备样件" },
];
+113
View File
@@ -21,6 +21,23 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/admin/keycloak-user-syncs": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/** Sync Keycloak User Directory */
post: operations["post_admin_keycloak_user_syncs"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/admin/project-provisions": {
parameters: {
query?: never;
@@ -5149,6 +5166,26 @@ export interface components {
*/
HistorySource: "scada_raw" | "scada_cleaned" | "realtime_simulation" | "analysis_simulation";
JsonValue: unknown;
/** KeycloakUserSyncIssue */
KeycloakUserSyncIssue: {
/** Reason */
reason: string;
/** Username */
username: string;
};
/** KeycloakUserSyncResponse */
KeycloakUserSyncResponse: {
/** Created */
created: number;
/** Issues */
issues?: components["schemas"]["KeycloakUserSyncIssue"][];
/** Scanned */
scanned: number;
/** Skipped */
skipped: number;
/** Updated */
updated: number;
};
/** LeakageIdentifyRequestRest */
LeakageIdentifyRequestRest: {
/**
@@ -5995,6 +6032,80 @@ export interface operations {
};
};
};
post_admin_keycloak_user_syncs: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Successful Response */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["KeycloakUserSyncResponse"];
};
};
/** @description Authentication required */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
/** @description Insufficient permission */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
/** @description Resource not found */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
/** @description Resource conflict */
409: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
/** @description Validation error */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
/** @description Dependency unavailable */
503: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ProblemDetails"];
};
};
};
};
post_admin_project_provisions: {
parameters: {
query?: never;
@@ -28768,6 +28879,8 @@ export interface operations {
accident_element: string[];
/** @description 已故障的阀门ID列表(可选) */
disabled_valves?: string[];
/** @description 事故要素类型;auto优先管段再节点;分析同名节点须指定node,纯管段分析可指定link */
accident_element_type?: "auto" | "link" | "node";
};
header: {
"X-Project-Id": string;