建立 React 认证会话 Provider 边界
This commit is contained in:
1 parent
dbd337a508
commit
010e77be91
17 files changed
+287
-69
No files matched your search
+17
-53
@@ -1,9 +1,9 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { readSidebarCollapsed, writeSidebarCollapsed } from './components/sidebarState';
|
||||
import { YdisksBrandIcon } from './components/YdisksLogo';
|
||||
import { initializeAdmin, login, logout, verifySession } from './app/features/session/api';
|
||||
import { ShieldCheck, ArrowRight, Loader2, User, Lock } from 'lucide-react';
|
||||
import AuthenticatedShell, { type DeliveryRuleTarget } from './app/shell/AuthenticatedShell';
|
||||
import { SessionProvider, useSession } from './app/providers/SessionProvider';
|
||||
|
||||
// 路由:URL path ↔ tab id。所有 SPA 路由统一挂 /app/ 前缀,避免和后端 API
|
||||
// 路径(/orders、/cards、/items 等)冲突——后者在 chi 里先注册,刷新会直接
|
||||
@@ -24,12 +24,11 @@ const TAB_TO_PATH: Record<string, string> = Object.fromEntries(
|
||||
); /* TAB_TO_PATH 表示TABTO当前路径。 */
|
||||
const tabFromPath = (): string => ROUTES[window.location.pathname] || 'dashboard'; /* tabFromPath 表示tabFrom当前路径。 */
|
||||
|
||||
const App: React.FC = () => {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false); /* [isLoggedIn, setIsLoggedIn] 表示isLoggedInsetIsLoggedIn。 */
|
||||
const [isAdmin, setIsAdmin] = useState(false); /* [isAdmin, setIsAdmin] 表示isAdminsetIsAdmin。 */
|
||||
// AppView 渲染认证表单、路由状态和认证成功后的应用壳。
|
||||
const AppView: React.FC = () => {
|
||||
// session 从 Provider 读取认证状态和会话操作,避免页面直接管理全局会话副作用。
|
||||
const { checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut } = useSession();
|
||||
const [activeTab, setActiveTab] = useState(tabFromPath); /* [activeTab, setActiveTab] 表示activeTabsetActiveTab。 */
|
||||
const [checkingAuth, setCheckingAuth] = useState(true); /* [checkingAuth, setCheckingAuth] 表示checkingAuthsetCheckingAuth。 */
|
||||
const [needsInit, setNeedsInit] = useState(false); /* [needsInit, setNeedsInit] 表示needsInitsetNeedsInit。 */
|
||||
const [username, setUsername] = useState(''); /* [username, setUsername] 表示usernamesetUsername。 */
|
||||
const [password, setPassword] = useState(''); /* [password, setPassword] 表示passwordsetPassword。 */
|
||||
const [loginLoading, setLoginLoading] = useState(false); /* [loginLoading, setLoginLoading] 表示login加载状态setLogin加载状态。 */
|
||||
@@ -58,39 +57,6 @@ const App: React.FC = () => {
|
||||
return () => window.removeEventListener('popstate', onPopState) /* 回调函数负责当前业务流程。 */;
|
||||
} /* 回调函数负责当前业务流程。 */, []);
|
||||
|
||||
// Check auth on mount
|
||||
useEffect(() => {
|
||||
verifySession()
|
||||
.then((res) => {
|
||||
if (res?.initialized === false) {
|
||||
setNeedsInit(true);
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setNeedsInit(false);
|
||||
if (res?.authenticated) {
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(res.is_admin === true);
|
||||
} else {
|
||||
setIsAdmin(false);
|
||||
}
|
||||
} /* 回调函数负责当前业务流程。 */)
|
||||
.catch(() => {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
} /* 回调函数负责当前业务流程。 */)
|
||||
.finally(() => setCheckingAuth(false) /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
const handleAuthLogoutEvent = () => {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
}; /* handleAuthLogoutEvent 表示handleAuthLogoutEvent。 */
|
||||
window.addEventListener('auth:logout', handleAuthLogoutEvent);
|
||||
return () => window.removeEventListener('auth:logout', handleAuthLogoutEvent) /* 回调函数负责当前业务流程。 */;
|
||||
} /* 回调函数负责当前业务流程。 */, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!checkingAuth && isLoggedIn && !isAdmin && activeTab === 'settings') {
|
||||
window.history.replaceState({}, '', TAB_TO_PATH.dashboard);
|
||||
@@ -104,11 +70,8 @@ const App: React.FC = () => {
|
||||
setLoginError('');
|
||||
|
||||
try {
|
||||
const res = await login({ username, password }); /* res 表示接口响应结果。 */
|
||||
if (res.success) {
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(res.is_admin === true);
|
||||
} else {
|
||||
const res = await signIn({ username, password }); /* res 表示接口响应结果。 */
|
||||
if (!res.success) {
|
||||
setLoginError(res.message || '登录失败');
|
||||
}
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
@@ -133,14 +96,11 @@ const App: React.FC = () => {
|
||||
|
||||
setInitializing(true);
|
||||
try {
|
||||
const res = await initializeAdmin(initialPassword); /* res 表示接口响应结果。 */
|
||||
const res = await initialize(initialPassword); /* res 表示接口响应结果。 */
|
||||
if (!res.success) {
|
||||
setInitializationError(res.message || '初始化失败,请重试');
|
||||
return;
|
||||
}
|
||||
setNeedsInit(false);
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(res.is_admin === true);
|
||||
setInitialPassword('');
|
||||
setInitialPasswordConfirm('');
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
@@ -153,12 +113,9 @@ const App: React.FC = () => {
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await logout();
|
||||
await signOut();
|
||||
} catch (err /* err 表示当前操作返回的错误。 */) {
|
||||
console.error('退出登录失败', err);
|
||||
} finally {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
}
|
||||
}; /* handleLogout 表示handleLogout。 */
|
||||
|
||||
@@ -335,6 +292,13 @@ const App: React.FC = () => {
|
||||
onDeliveryTargetHandled={handleDeliveryTargetHandled}
|
||||
/>
|
||||
);
|
||||
}; /* App 表示App。 */
|
||||
}; /* AppView 表示认证页面和应用壳视图。 */
|
||||
|
||||
// App 在根部装配 SessionProvider,确保所有认证状态共享同一生命周期。
|
||||
const App: React.FC = () => (
|
||||
<SessionProvider>
|
||||
<AppView />
|
||||
</SessionProvider>
|
||||
);
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,107 @@
|
||||
// @vitest-environment jsdom
|
||||
import type { ReactNode } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { initializeAdmin, login, logout, verifySession } from '../features/session/api';
|
||||
import { SessionProvider, useSession } from './SessionProvider';
|
||||
|
||||
vi.mock('../features/session/api', /* sessionApiMockFactory 提供会话 Provider 的确定性 API 替身。 */ () => ({
|
||||
initializeAdmin: vi.fn(),
|
||||
login: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
verifySession: vi.fn(),
|
||||
}));
|
||||
|
||||
// initializeMock 是首次管理员初始化请求的可控替身。
|
||||
const initializeMock = vi.mocked(initializeAdmin);
|
||||
// loginMock 是登录请求的可控替身。
|
||||
const loginMock = vi.mocked(login);
|
||||
// logoutMock 是注销请求的可控替身。
|
||||
const logoutMock = vi.mocked(logout);
|
||||
// verifySessionMock 是会话校验请求的可控替身。
|
||||
const verifySessionMock = vi.mocked(verifySession);
|
||||
|
||||
// sessionWrapper 将被测 Hook 装配到真实的 SessionProvider 中。
|
||||
const sessionWrapper = ({ children }: { /** children 表示测试组件树的 React 子节点。 */ children: ReactNode }) => (
|
||||
<SessionProvider>{children}</SessionProvider>
|
||||
);
|
||||
|
||||
describe('SessionProvider', /* 当前回调验证认证 Provider 的状态和生命周期。 */ () => {
|
||||
beforeEach(/* 当前回调重置会话 API 替身和默认响应。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
verifySessionMock.mockResolvedValue({ authenticated: false, initialized: true });
|
||||
loginMock.mockResolvedValue({ success: false, message: '登录失败' });
|
||||
initializeMock.mockResolvedValue({ success: false, message: '初始化失败' });
|
||||
logoutMock.mockResolvedValue({ success: true });
|
||||
});
|
||||
|
||||
test('校验管理员会话并响应全局注销事件', /* 当前回调验证会话校验和全局注销事件。 */ async () => {
|
||||
verifySessionMock.mockResolvedValueOnce({ authenticated: true, initialized: true, is_admin: true });
|
||||
// hook 是已认证会话 Hook 的渲染结果。
|
||||
const hook = renderHook(/* hookFactory 创建已认证会话 Hook。 */ () => useSession(), { wrapper: sessionWrapper });
|
||||
|
||||
await waitFor(/* authReadyAssertion 等待会话校验完成。 */ () => expect(hook.result.current.checkingAuth).toBe(false));
|
||||
expect(hook.result.current.isLoggedIn).toBe(true);
|
||||
expect(hook.result.current.isAdmin).toBe(true);
|
||||
expect(hook.result.current.needsInit).toBe(false);
|
||||
|
||||
act(/* logoutEventAction 发布全局注销事件。 */ () => window.dispatchEvent(new Event('auth:logout')));
|
||||
expect(hook.result.current.isLoggedIn).toBe(false);
|
||||
expect(hook.result.current.isAdmin).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('未初始化系统会进入首次初始化状态', /* 当前回调验证首次管理员初始化分支。 */ async () => {
|
||||
verifySessionMock.mockResolvedValueOnce({ authenticated: false, initialized: false });
|
||||
// hook 是未初始化会话 Hook 的渲染结果。
|
||||
const hook = renderHook(/* hookFactory 创建未初始化会话 Hook。 */ () => useSession(), { wrapper: sessionWrapper });
|
||||
|
||||
await waitFor(/* authReadyAssertion 等待未初始化校验完成。 */ () => expect(hook.result.current.checkingAuth).toBe(false));
|
||||
expect(hook.result.current.needsInit).toBe(true);
|
||||
expect(hook.result.current.isLoggedIn).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('登录和首次初始化成功后更新认证状态', /* 当前回调验证登录和初始化成功状态。 */ async () => {
|
||||
// hook 是认证操作 Hook 的渲染结果。
|
||||
const hook = renderHook(/* hookFactory 创建认证操作 Hook。 */ () => useSession(), { wrapper: sessionWrapper });
|
||||
await waitFor(/* authReadyAssertion 等待认证操作测试准备完成。 */ () => expect(hook.result.current.checkingAuth).toBe(false));
|
||||
|
||||
loginMock.mockResolvedValueOnce({ success: true, username: 'admin', is_admin: true });
|
||||
await act(/* signInAction 执行登录操作。 */ async () => {
|
||||
// response 表示登录操作返回的认证结果。
|
||||
const response = await hook.result.current.signIn({ username: 'admin', password: 'password' });
|
||||
expect(response.success).toBe(true);
|
||||
});
|
||||
expect(hook.result.current.isLoggedIn).toBe(true);
|
||||
expect(hook.result.current.isAdmin).toBe(true);
|
||||
|
||||
initializeMock.mockResolvedValueOnce({ success: true, username: 'admin', is_admin: true });
|
||||
await act(/* initializeAction 执行首次初始化操作。 */ async () => {
|
||||
// response 表示首次初始化返回的认证结果。
|
||||
const response = await hook.result.current.initialize('new-password');
|
||||
expect(response.success).toBe(true);
|
||||
});
|
||||
expect(hook.result.current.needsInit).toBe(false);
|
||||
expect(initializeMock).toHaveBeenCalledWith('new-password');
|
||||
hook.unmount();
|
||||
});
|
||||
|
||||
test('注销请求失败时仍清理本地认证状态并向调用方抛错', /* 当前回调验证注销失败后的本地收束。 */ async () => {
|
||||
loginMock.mockResolvedValueOnce({ success: true, username: 'admin', is_admin: false });
|
||||
// hook 是注销失败场景 Hook 的渲染结果。
|
||||
const hook = renderHook(/* hookFactory 创建注销失败场景 Hook。 */ () => useSession(), { wrapper: sessionWrapper });
|
||||
await waitFor(/* authReadyAssertion 等待注销测试准备完成。 */ () => expect(hook.result.current.checkingAuth).toBe(false));
|
||||
await act(/* signInAction 建立待注销的已认证状态。 */ async () => {
|
||||
await hook.result.current.signIn({ username: 'admin', password: 'password' });
|
||||
});
|
||||
logoutMock.mockRejectedValueOnce(new Error('网络不可用'));
|
||||
|
||||
await act(/* signOutAction 执行会失败但应清理本地状态的注销操作。 */ async () => {
|
||||
await expect(hook.result.current.signOut()).rejects.toThrow('网络不可用');
|
||||
});
|
||||
expect(hook.result.current.isLoggedIn).toBe(false);
|
||||
expect(hook.result.current.isAdmin).toBe(false);
|
||||
hook.unmount();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from 'react';
|
||||
import { initializeAdmin, login, logout, verifySession } from '../features/session/api';
|
||||
import type { SessionResponse } from '../../types';
|
||||
|
||||
// LoginCredentials 描述登录表单提交给会话服务的凭据字段。
|
||||
export interface LoginCredentials {
|
||||
// username 表示管理员登录名。
|
||||
username: string;
|
||||
// password 表示管理员登录密码。
|
||||
password: string;
|
||||
}
|
||||
|
||||
// SessionContextValue 描述认证状态和会话操作的统一 Provider 契约。
|
||||
export interface SessionContextValue {
|
||||
// checkingAuth 表示首次会话校验是否尚未完成。
|
||||
checkingAuth: boolean;
|
||||
// isLoggedIn 表示当前浏览器会话是否已认证。
|
||||
isLoggedIn: boolean;
|
||||
// isAdmin 表示当前已认证用户是否为管理员。
|
||||
isAdmin: boolean;
|
||||
// needsInit 表示后端尚未完成首次管理员初始化。
|
||||
needsInit: boolean;
|
||||
// signIn 执行登录并在成功后更新认证状态。
|
||||
signIn: (credentials: LoginCredentials) => Promise<SessionResponse>;
|
||||
// initialize 执行首次管理员初始化并在成功后更新认证状态。
|
||||
initialize: (password: string) => Promise<SessionResponse>;
|
||||
// signOut 注销后端会话并清理本地认证状态。
|
||||
signOut: () => Promise<void>;
|
||||
}
|
||||
|
||||
// SessionContext 保存认证状态,避免页面组件直接依赖会话 API 和全局事件。
|
||||
const SessionContext = createContext<SessionContextValue | undefined>(undefined);
|
||||
|
||||
// SessionProvider 提供会话校验、认证操作和全局注销事件的统一生命周期边界。
|
||||
export const SessionProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
|
||||
// [isLoggedIn, setIsLoggedIn] 保存当前会话是否已经通过认证。
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
// [isAdmin, setIsAdmin] 保存当前会话的管理员权限。
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
// [checkingAuth, setCheckingAuth] 保存首次会话校验是否仍在进行。
|
||||
const [checkingAuth, setCheckingAuth] = useState(true);
|
||||
// [needsInit, setNeedsInit] 保存系统是否需要首次管理员初始化。
|
||||
const [needsInit, setNeedsInit] = useState(false);
|
||||
|
||||
// clearSession 将本地认证状态恢复为未登录且非管理员。
|
||||
const clearSession = () => {
|
||||
setIsLoggedIn(false);
|
||||
setIsAdmin(false);
|
||||
};
|
||||
|
||||
useEffect(/* 当前回调管理会话校验请求和全局注销监听。 */ () => {
|
||||
// controller 负责取消组件卸载后的会话校验请求。
|
||||
const controller = new AbortController();
|
||||
// active 表示当前 Provider 是否仍然允许异步结果更新状态。
|
||||
let active = true;
|
||||
|
||||
verifySession({ signal: controller.signal })
|
||||
.then(/* 当前回调处理会话校验结果。 */ response /* response 表示会话校验响应。 */ => {
|
||||
if (!active) return;
|
||||
if (response?.initialized === false) {
|
||||
setNeedsInit(true);
|
||||
clearSession();
|
||||
return;
|
||||
}
|
||||
|
||||
setNeedsInit(false);
|
||||
if (response?.authenticated) {
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(response.is_admin === true);
|
||||
} else {
|
||||
clearSession();
|
||||
}
|
||||
})
|
||||
.catch(/* 当前回调处理会话校验失败。 */ error /* error 表示会话校验错误。 */ => {
|
||||
if (!active || (error instanceof DOMException && error.name === 'AbortError')) return;
|
||||
setNeedsInit(false);
|
||||
clearSession();
|
||||
})
|
||||
.finally(/* 当前回调收束会话校验加载状态。 */ () => {
|
||||
if (active) setCheckingAuth(false);
|
||||
});
|
||||
|
||||
// handleAuthLogoutEvent 响应其他页面发出的全局注销通知。
|
||||
const handleAuthLogoutEvent = () => clearSession();
|
||||
window.addEventListener('auth:logout', handleAuthLogoutEvent);
|
||||
|
||||
return /* 当前回调清理会话校验和全局事件资源。 */ () => {
|
||||
active = false;
|
||||
controller.abort();
|
||||
window.removeEventListener('auth:logout', handleAuthLogoutEvent);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// signIn 调用登录接口,并只在服务端确认成功后更新认证状态。
|
||||
const signIn = async (credentials: LoginCredentials): Promise<SessionResponse> => {
|
||||
// response 表示登录接口返回的认证结果。
|
||||
const response = await login(credentials);
|
||||
if (response.success) {
|
||||
setNeedsInit(false);
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(response.is_admin === true);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
// initialize 调用首次初始化接口,并在成功后建立管理员会话。
|
||||
const initialize = async (password: string): Promise<SessionResponse> => {
|
||||
// response 表示首次初始化接口返回的认证结果。
|
||||
const response = await initializeAdmin(password);
|
||||
if (response.success) {
|
||||
setNeedsInit(false);
|
||||
setIsLoggedIn(true);
|
||||
setIsAdmin(response.is_admin === true);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
// signOut 先请求后端注销,再无条件清理本地状态;接口失败会继续抛给界面记录。
|
||||
const signOut = async (): Promise<void> => {
|
||||
try {
|
||||
await logout();
|
||||
} finally {
|
||||
clearSession();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={{ checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut }}>
|
||||
{children}
|
||||
</SessionContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
// useSession 读取认证 Provider;缺少 Provider 时立即抛出装配错误。
|
||||
export const useSession = (): SessionContextValue => {
|
||||
// context 表示当前组件树中装配的会话上下文值。
|
||||
const context = useContext(SessionContext);
|
||||
if (!context) {
|
||||
throw new Error('useSession 必须在 SessionProvider 内使用');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
@@ -56,9 +56,11 @@ describe('frontend navigation routing', () => {
|
||||
|
||||
test('logout button invalidates the backend session before clearing UI state', () => {
|
||||
const app = readFrontendFile('App.tsx'); /* app 表示app。 */
|
||||
const sessionProvider = readFrontendFile('app/providers/SessionProvider.tsx'); /* sessionProvider 表示认证 Provider 源码。 */
|
||||
|
||||
expect(app).toContain('import { initializeAdmin, login, logout, verifySession }');
|
||||
expect(app).toContain('await logout();');
|
||||
expect(app).toContain("import { SessionProvider, useSession }");
|
||||
expect(sessionProvider).toContain('await logout();');
|
||||
expect(sessionProvider).toContain("window.addEventListener('auth:logout'");
|
||||
expect(app).toContain('onLogout={handleLogout}');
|
||||
} /* 回调函数负责当前业务流程。 */);
|
||||
|
||||
@@ -77,12 +79,13 @@ describe('frontend navigation routing', () => {
|
||||
|
||||
test('admin-only settings navigation is gated by session role', () => {
|
||||
const app = readFrontendFile('App.tsx'); /* app 表示app。 */
|
||||
const sessionProvider = readFrontendFile('app/providers/SessionProvider.tsx'); /* sessionProvider 表示认证 Provider 源码。 */
|
||||
const shell = readFrontendFile('app/shell/AuthenticatedShell.tsx'); /* shell 表示认证后应用壳源码。 */
|
||||
const sidebar = readFrontendFile('components/Sidebar.tsx'); /* sidebar 表示sidebar。 */
|
||||
const settingsHook = readFrontendFile('app/features/settings/hooks.ts'); /* settingsHook 表示settingsHook。 */
|
||||
|
||||
expect(app).toContain('const [isAdmin, setIsAdmin] = useState(false)');
|
||||
expect(app).toContain('setIsAdmin(res.is_admin === true)');
|
||||
expect(app).toContain('const { checkingAuth, isLoggedIn, isAdmin, needsInit, signIn, initialize, signOut } = useSession();');
|
||||
expect(sessionProvider).toContain('setIsAdmin(response.is_admin === true)');
|
||||
expect(app).toContain("activeTab === 'settings'");
|
||||
expect(shell).toContain('isAdmin ? <Settings /> : <Dashboard />');
|
||||
expect(sidebar).toContain('isAdmin = false');
|
||||
|
||||
Reference in new issue
Block a user