import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
/**
* PrivateRoute Component
*
* A wrapper for routes that require authentication.
* Redirects to login if user is not authenticated.
*/
export const PrivateRoute = ({ children }) => {
const { user, loading } = useAuth();
const location = useLocation();
// Show loading state while checking authentication
if (loading) {
return (
);
}
// Redirect to login if not authenticated
if (!user) {
// Save the location they were trying to go to
return ;
}
// Render the protected route
return children;
};
/**
* RoleRoute Component
*
* A wrapper for routes that require specific user roles.
* Redirects to access denied page if user doesn't have required role.
*
* @param {array} roles - Array of allowed roles
* @param {React.ReactNode} children - Child components to render
*/
export const RoleRoute = ({ roles, children }) => {
const { user, loading } = useAuth();
// Show loading state while checking authentication
if (loading) {
return (
);
}
// Check if user has required role
if (user && roles.includes(user.user_type)) {
return children;
}
// Redirect to access denied page
return ;
};
export default PrivateRoute;