38 lines
980 B
TypeScript
38 lines
980 B
TypeScript
import React from 'react';
|
|
import { Navigate } from '@tanstack/react-router';
|
|
import { useAuth } from '../../contexts/AuthContext';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
requiredRole?: 'admin' | 'contributor' | 'user';
|
|
redirectTo?: string;
|
|
}
|
|
|
|
export function ProtectedRoute({
|
|
children,
|
|
requiredRole,
|
|
redirectTo = '/'
|
|
}: ProtectedRouteProps) {
|
|
const { isAuthenticated, user, isLoading } = useAuth();
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="flex items-center justify-center min-h-screen">
|
|
<div className="text-center">
|
|
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
|
|
<p className="mt-4 text-muted-foreground">Loading...</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (!isAuthenticated) {
|
|
return <Navigate to={redirectTo} />;
|
|
}
|
|
|
|
if (requiredRole && user?.role !== requiredRole) {
|
|
return <Navigate to="/" />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
} |