All files / components ProtectedRoute.tsx

100% Statements 9/9
100% Branches 4/4
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43                              19x 19x   19x   13x       19x 4x                     15x 6x     9x    
/**
 * Protected route wrapper
 * Redirects to login if user is not authenticated
 */
 
import { useEffect } from 'react';
import { Navigate, useLocation } from 'react-router';
import { useAuthStore } from '@/stores/auth.store';
import { Loader2 } from 'lucide-react';
 
interface ProtectedRouteProps {
    children: React.ReactNode;
}
 
export default function ProtectedRoute({ children }: ProtectedRouteProps) {
    const location = useLocation();
    const { isAuthenticated, isLoading, restoreSession } = useAuthStore();
 
    useEffect(() => {
        // Restore session on mount
        restoreSession();
    }, [restoreSession]);
 
    // Show loading state while checking authentication
    if (isLoading) {
        return (
            <div className="flex min-h-screen items-center justify-center bg-background">
                <div className="text-center">
                    <Loader2 className="h-8 w-8 animate-spin text-primary mx-auto" />
                    <p className="mt-4 text-muted-foreground">Loading...</p>
                </div>
            </div>
        );
    }
 
    // Redirect to login if not authenticated
    if (!isAuthenticated) {
        return <Navigate to="/admin/login" state={{ from: location }} replace />;
    }
 
    return <>{children}</>;
}