File size: 611 Bytes
aa06156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { useAuth } from '../context/AuthContext';
import { Navigate, Outlet } from 'react-router-dom';
import { toast } from 'react-toastify';

export default function PrivateRoute({ roles, children }) {
  const { user, isAuthenticated, hasRole } = useAuth();

  if (!isAuthenticated()) {
    toast.error('لطفا ابتدا وارد شوید');
    return <Navigate to="/login" />;
  }

  if (roles && !roles.some(role => hasRole(role))) {
    toast.error('شما مجوز دسترسی به این صفحه را ندارید');
    return <Navigate to="/" />;
  }

  return children ? children : <Outlet />;
}