fix(frontend): Fix auth hydration and auto-redirect to login
Fix issue where unauthenticated users were not automatically redirected to the login page. Root Cause: - authStore.ts: isLoading was not set to false after hydration - AuthGuard.tsx: Used isLoading instead of isHydrated for checks Changes: - Set isLoading = false in authStore onRehydrateStorage callback - Changed AuthGuard to use isHydrated instead of isLoading - Added console log for redirect debugging This ensures: - Hydration completes with correct loading state - Unauthenticated users are immediately redirected to /login - More explicit state management with isHydrated 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -7,16 +7,17 @@ import { useCurrentUser } from '@/lib/hooks/useAuth';
|
|||||||
|
|
||||||
export function AuthGuard({ children }: { children: React.ReactNode }) {
|
export function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { isAuthenticated, isLoading } = useAuthStore();
|
const { isAuthenticated, isHydrated } = useAuthStore();
|
||||||
const { isLoading: isUserLoading } = useCurrentUser();
|
const { isLoading: isUserLoading } = useCurrentUser();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isLoading && !isUserLoading && !isAuthenticated) {
|
if (isHydrated && !isUserLoading && !isAuthenticated) {
|
||||||
|
console.log('[AuthGuard] Redirecting to login - user not authenticated');
|
||||||
router.push('/login');
|
router.push('/login');
|
||||||
}
|
}
|
||||||
}, [isAuthenticated, isLoading, isUserLoading, router]);
|
}, [isAuthenticated, isHydrated, isUserLoading, router]);
|
||||||
|
|
||||||
if (isLoading || isUserLoading) {
|
if (!isHydrated || isUserLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen items-center justify-center">
|
<div className="flex min-h-screen items-center justify-center">
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
|
|||||||
@@ -57,9 +57,11 @@ export const useAuthStore = create<AuthState>()(
|
|||||||
}
|
}
|
||||||
|
|
||||||
state.isHydrated = true;
|
state.isHydrated = true;
|
||||||
|
state.isLoading = false; // 水合完成后停止 loading
|
||||||
console.log('[AuthStore] Hydration completed', {
|
console.log('[AuthStore] Hydration completed', {
|
||||||
userId: state.user?.id,
|
userId: state.user?.id,
|
||||||
isAuthenticated: state.isAuthenticated
|
isAuthenticated: state.isAuthenticated,
|
||||||
|
isLoading: state.isLoading
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in New Issue
Block a user