32 lines
916 B
TypeScript
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}</>;
|
|
}
|