How can i prevent certain type of user role to access other role route using React Router Dom V6

26 Views Asked by At

In an application i have 2 types of users vendor and buyer want to manage the routing in such a away the vendor can not access buyer pages and vice versa using React Router Dom V6. Attempt to do so should route to an access denied page.

Login logic from the login page

 if (res.data.data.user?.role?.name.toLowerCase() === "vendor") {
      navigate("/dashboard")             
}
else {
   navigate("/buyer-dashboard")
}

App.jsx


<BrowserRouter>
            <BuyerRoute />

            <VendorRoute />

            <PublicRoute />
</BrowserRouter>

PublicRoute.jsx

<Routes>
     
      <Route index element={<Login />} />
      <Route path='/signup' element={<SignUp />} />
      <Route path='/email-confirmation' element={<Confirmation />} />
      <Route path='/forget-password' element={<ForgetPassword />} />
      <Route path='/set-password/:email' element={<SetPassword />} />
      <Route path='*' element={<>404</>} />
    </Routes>

BuyerRoute.jsx

<Routes>
      <Route path="/buyer-dashboard" element={<Dashboard />} />
      <Route path="/other" element={< Other />} />
</Routes>

VendorRoute.jsx

<Routes>
      <Route path="/dashboard" element={<VendorDashboard />} />
      <Route path="/items" element={< Items />} />
</Routes>

Login successfully route to the expected page, buy i change the route in the address bar i am able to navigate to dashboard when i logged in as a buyer.

1

There are 1 best solutions below

0
MOIZ On

For the approach you want in your app you need to use protected routes you can learn more in this blog : https://blog.logrocket.com/authentication-react-router-v6/

Create routes using createBrowserRouter

import { createBrowserRouter } from 'react-router-dom';
//import all the page components here 

export const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
  {
    index: true,
    element: <Login />,
  },
  {
    path: 'signup',
    element: <SignUp />,
  },
  {
    path: 'dashboard',
    element: (
     <ProtectedRoute allowedRoles={roles.vendor}>
     <VendorDashboard />
     </ProtectedRoute>
   ),
  },
  {
    path: 'items',
    element:(
    <ProtectedRoute allowedRoles={roles.vendor}>
     <Items />
    </ProtectedRoute>
),
  },
  {
    path: 'buyer-dashboard',
    element:(
    <ProtectedRoute allowedRoles={roles.buyer}>
     <Dashboard />
    </ProtectedRoute>
  ),
  },
  {
    path: 'other',
    element:(
    <ProtectedRoute allowedRoles={roles.buyer}>
     <Other />
    </ProtectedRoute>
   ),
  },
],},]);     

const roles = {
buyer: ['buyer-dashboard', 'other'],
vendor: ['dashboard', 'items'],
};

Make a function to retrieve to roles of the user on login

const getUserRole = () => {
 return 'superAdmin'; 
};

now make a component for protected route

import { Navigate } from 'react-router-dom';

const ProtectedRoute = ({ children, allowedRoles }) => {
const userRole = getUserRole();
const isAuthenticated = true;

if (!isAuthenticated) {
  return <Navigate to="/login" replace />;
}

if (!allowedRoles.includes(userRole)) {
  return <Navigate to="/unauthorized" replace />; 
}

 return children // <Outlet />; tyou can use Outlet here to 
};

export default ProtectedRoute;