fix: bootstrap session after password login

This commit is contained in:
wren
2026-04-29 15:58:59 +08:00
parent 0369de68cc
commit 7dbeaac5f8
3 changed files with 502 additions and 520 deletions
+13 -9
View File
@@ -11,9 +11,11 @@ import { isAuthenticated } from '~/utils/auth-storage';
interface ClientAuthGuardProps {
isPublicPath: boolean;
frontendJWT?: string;
userInfo?: Record<string, unknown>;
}
export function ClientAuthGuard({ isPublicPath }: ClientAuthGuardProps) {
export function ClientAuthGuard({ isPublicPath, frontendJWT, userInfo }: ClientAuthGuardProps) {
const navigate = useNavigate();
const location = useLocation();
@@ -29,15 +31,17 @@ export function ClientAuthGuard({ isPublicPath }: ClientAuthGuardProps) {
return;
}
// 检查客户端是否已认证(localStorage 中有 token
// 优先用服务端 session 回传的数据回填 localStorage,避免刚登录时客户端误判未登录
const token = localStorage.getItem('access_token');
const authenticated = isAuthenticated();
if (!token && frontendJWT) {
localStorage.setItem('access_token', frontendJWT);
if (userInfo) {
localStorage.setItem('user_info', JSON.stringify(userInfo));
}
console.log('✅ [Auth Guard] 已根据服务端 session 回填本地认证数据');
}
// console.log('🔍 [Auth Guard] 认证检查', {
// token: token ? `${token.substring(0, 20)}...` : null,
// authenticated,
// pathname: location.pathname
// });
const authenticated = isAuthenticated() || !!frontendJWT;
if (!authenticated) {
console.log('🔒 [Auth Guard] 未认证,重定向到登录页');
@@ -50,7 +54,7 @@ export function ClientAuthGuard({ isPublicPath }: ClientAuthGuardProps) {
} else {
// console.log('✅ [Auth Guard] 已认证,允许访问');
}
}, [isPublicPath, navigate, location.pathname]);
}, [isPublicPath, navigate, location.pathname, frontendJWT, userInfo]);
// 这个组件不渲染任何内容
return null;