33 lines
955 B
TypeScript
33 lines
955 B
TypeScript
import { Navigate } from 'react-router-dom';
|
|
import { useAuth } from '@/features/auth/hooks/useAuth';
|
|
import { useAuthStore } from '@/features/auth/store/authStore';
|
|
import { useEffect, useState } from 'react';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
}
|
|
|
|
/**
|
|
* Protects authenticated routes. Redirects to /login if not authenticated.
|
|
* Uses authStore.isAuthenticated (hydrated by AuthProvider via refreshUser with httpOnly cookies).
|
|
*/
|
|
export function ProtectedRoute({ children }: ProtectedRouteProps) {
|
|
const { isAuthenticated } = useAuth();
|
|
const [isChecking, setIsChecking] = useState(true);
|
|
const { isLoading } = useAuthStore();
|
|
|
|
useEffect(() => {
|
|
const timer = setTimeout(() => setIsChecking(false), 200);
|
|
return () => clearTimeout(timer);
|
|
}, []);
|
|
|
|
if (isChecking || isLoading) {
|
|
return null;
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
return <Navigate to="/login" replace />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|