40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import React from 'react';
|
|
import { Navigate } from 'react-router-dom';
|
|
import { useAuth } from '../context/useAuth';
|
|
import type { UserRole } from '../types';
|
|
import { RefreshCw } from 'lucide-react';
|
|
|
|
interface ProtectedRouteProps {
|
|
children: React.ReactNode;
|
|
allowedRoles?: UserRole[];
|
|
requireEdit?: boolean;
|
|
redirectTo?: string;
|
|
}
|
|
|
|
/**
|
|
* ProtectedRoute component that restricts access based on user role
|
|
* @param allowedRoles - Array of roles that can access the route
|
|
* @param requireEdit - If true, only users who can edit (not guests) can access
|
|
* @param redirectTo - Where to redirect if access is denied (default: '/')
|
|
*/
|
|
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
|
|
children,
|
|
allowedRoles,
|
|
requireEdit = false,
|
|
redirectTo = '/',
|
|
}) => {
|
|
const { appUser, canEdit } = useAuth();
|
|
|
|
// Check role-based access
|
|
if (allowedRoles && appUser && !allowedRoles.includes(appUser.role)) {
|
|
return <Navigate to={redirectTo} replace />;
|
|
}
|
|
|
|
// Check edit permission
|
|
if (requireEdit && !canEdit()) {
|
|
return <Navigate to={redirectTo} replace />;
|
|
}
|
|
|
|
return <>{children}</>;
|
|
};
|