erp-core-frontend-v2/src/app/router/ProtectedRoute.tsx
rckrdmrd b30f3339bd Migración desde erp-core/frontend - Estándar multi-repo v2
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 08:10:41 -06:00

32 lines
916 B
TypeScript

import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '@stores/useAuthStore';
import { FullPageSpinner } from '@components/atoms/Spinner';
interface ProtectedRouteProps {
children: React.ReactNode;
requiredRoles?: string[];
}
export function ProtectedRoute({ children, requiredRoles }: ProtectedRouteProps) {
const location = useLocation();
const { isAuthenticated, isLoading, user } = useAuthStore();
if (isLoading) {
return <FullPageSpinner />;
}
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
if (requiredRoles && requiredRoles.length > 0 && user) {
const userRoleName = user.role?.name;
const hasRequiredRole = userRoleName ? requiredRoles.includes(userRoleName) : false;
if (!hasRequiredRole) {
return <Navigate to="/unauthorized" replace />;
}
}
return <>{children}</>;
}