32 lines
851 B
TypeScript
32 lines
851 B
TypeScript
import { Navigate, useLocation } from 'react-router-dom';
|
|
import { useAuth } from '@/hooks/useAuth';
|
|
import { Loader2 } from 'lucide-react';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
adminOnly?: boolean;
|
|
}
|
|
|
|
export default function ProtectedRoute({ children, adminOnly = false }: ProtectedRouteProps) {
|
|
const { isAuthenticated, isLoading, user } = useAuth();
|
|
const location = useLocation();
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center bg-gray-bg">
|
|
<Loader2 className="w-8 h-8 text-primary animate-spin" />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
return <Navigate to="/login" state={{ from: location }} replace />;
|
|
}
|
|
|
|
if (adminOnly && user?.role !== 'admin') {
|
|
return <Navigate to="/dashboard" replace />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
}
|