52 lines
2.1 KiB
TypeScript
52 lines
2.1 KiB
TypeScript
|
|
// src/routes/SectionProtectedRoute.tsx
|
||
|
|
import React from 'react';
|
||
|
|
import { Navigate, Outlet } from 'react-router-dom';
|
||
|
|
import { useAuth } from '../contexts/AuthContext';
|
||
|
|
import { usePermissions } from '../hooks/usePermissions';
|
||
|
|
import { Box, CircularProgress } from '@mui/material';
|
||
|
|
|
||
|
|
interface SectionProtectedRouteProps {
|
||
|
|
requiredPermission: string;
|
||
|
|
sectionName: string;
|
||
|
|
children?: React.ReactNode;
|
||
|
|
}
|
||
|
|
|
||
|
|
const SectionProtectedRoute: React.FC<SectionProtectedRouteProps> = ({ requiredPermission, sectionName, children }) => {
|
||
|
|
const { isAuthenticated, isLoading: authIsLoading } = useAuth(); // isLoading de AuthContext
|
||
|
|
const { tienePermiso, isSuperAdmin, currentUser } = usePermissions();
|
||
|
|
|
||
|
|
if (authIsLoading) { // Esperar a que el AuthContext termine su carga inicial
|
||
|
|
return (
|
||
|
|
<Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '80vh' }}>
|
||
|
|
<CircularProgress />
|
||
|
|
</Box>
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!isAuthenticated) {
|
||
|
|
return <Navigate to="/login" replace />;
|
||
|
|
}
|
||
|
|
|
||
|
|
// En este punto, si está autenticado, currentUser debería estar disponible.
|
||
|
|
// Si currentUser pudiera ser null aun estando autenticado (poco probable con tu AuthContext),
|
||
|
|
// se necesitaría un manejo adicional o un spinner aquí.
|
||
|
|
if (!currentUser) {
|
||
|
|
// Esto sería un estado inesperado si isAuthenticated es true.
|
||
|
|
// Podrías redirigir a login o mostrar un error genérico.
|
||
|
|
console.error("SectionProtectedRoute: Usuario autenticado pero currentUser es null.");
|
||
|
|
return <Navigate to="/login" replace />; // O un error más específico
|
||
|
|
}
|
||
|
|
|
||
|
|
const canAccessSection = isSuperAdmin || tienePermiso(requiredPermission);
|
||
|
|
|
||
|
|
if (!canAccessSection) {
|
||
|
|
console.error('SectionProtectedRoute: Usuario autenticado pero sin acceso a sección ', sectionName);
|
||
|
|
return <Navigate to="/" replace />;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Si children se proporciona (como <SectionProtectedRoute><IndexPage/></SectionProtectedRoute>), renderiza children.
|
||
|
|
// Si no (como <Route element={<SectionProtectedRoute ... />} > <Route .../> </Route>), renderiza Outlet.
|
||
|
|
return children ? <>{children}</> : <Outlet />;
|
||
|
|
};
|
||
|
|
|
||
|
|
export default SectionProtectedRoute;
|