21 lines
637 B
JavaScript
21 lines
637 B
JavaScript
import React from "react";
|
|
import { Navigate } from "react-router-dom";
|
|
import { useAuth } from "./AuthContext"; // Utilisation du contexte d'authentification
|
|
|
|
function ProtectedRoute({ element, allowedRoles }) {
|
|
const { token, user } = useAuth(); // Vérifier si un token existe, donc si l'utilisateur est authentifié
|
|
|
|
// Si l'utilisateur n'est pas authentifié, redirigez-le vers la page de login
|
|
if (!token) {
|
|
return <Navigate to="/login" />;
|
|
}
|
|
if(user){
|
|
if (allowedRoles && !allowedRoles.includes(user?.role)) {
|
|
return <Navigate to="/" />;
|
|
}
|
|
return element;
|
|
}
|
|
}
|
|
|
|
export default ProtectedRoute;
|