24 lines
532 B
JavaScript
24 lines
532 B
JavaScript
import { useContext } from "react";
|
|
import { Navigate } from "react-router-dom";
|
|
import { AuthContext } from "../context/AuthContext";
|
|
|
|
export default function RoleGuard({ allowed, children }) {
|
|
const { role } = useContext(AuthContext);
|
|
|
|
if (!role) return <Navigate to="/login" />;
|
|
if (!allowed.includes(role)) return <Navigate to="/" />;
|
|
|
|
return children;
|
|
}
|
|
|
|
|
|
function usageExample() {
|
|
<Route
|
|
path="/admin"
|
|
element={
|
|
<RoleGuard allowed={[ROLES.ADMIN]}>
|
|
<AdminPanel />
|
|
</RoleGuard>
|
|
}
|
|
/>
|
|
} |