All files / src/components/RequireAuth RequireAuth.tsx

100% Statements 10/10
100% Branches 8/8
100% Functions 3/3
100% Lines 8/8

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                                  6x 6x 6x     6x   2x       4x   2x       2x    
import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore, type UserRole } from '../../stores/useAuthStore';
import type { JSX } from 'react';
 
interface RequireAuthProps {
  children: JSX.Element;
  requiredRole?: UserRole;
  loginPath?: string;
  unauthorizedPath?: string;
}
 
export function RequireAuth({
  children,
  requiredRole,
  loginPath = '/login',
  unauthorizedPath = '/unauthorized',
}: RequireAuthProps): JSX.Element {
  const authToken = useAuthStore(state => state.authToken);
  const role = useAuthStore(state => state.role);
  const location = useLocation();
 
  // 1) Vérifier si authentifié
  if (!authToken) {
    // Redirige vers login, on peut passer l’URL d’origine dans state
    return <Navigate to={loginPath} state={{ from: location }} replace />;
  }
 
  // 2) Si un rôle est requis, vérifier
  if (requiredRole && role !== requiredRole) {
    // Authentifié mais pas le bon rôle
    return <Navigate to={unauthorizedPath} replace />;
  }
 
  // 3) Tout est ok
  return children;
}