-2

I am using react-redux-saga. How can I create routing for many roles. Roles contains the array of the resources and their respective permissions.

Sushant
  • 33
  • 6
  • 1
    Please don't re-post the same question as https://stackoverflow.com/questions/71751113 just with less info. – timotgl Apr 06 '22 at 10:15

1 Answers1

-1

Create component ProtectRoute which tell the router whether or not it should allow navigation to a requested route. // ProtectRoute.js

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

export function PrivateRoute(props) {
  const location = useLocation()
  const {
    roles,               // {string[]} permitted roles
    unauthenticatedPath  // fallback path when don't have permission
  } = props
  const { loading, isAuthenticated, hasRole } = // get auth state from store or context

  const unauthorized = useCallback(() => {
    return !(isAuthenticated && (!roles || hasRole(roles)))   // check role
  }, [isAuthenticated, roles, hasRole])

  if (unauthorized()) {
    if (loading) {
      return <Loading />
    }
    return <Navigate to={unauthenticatedPath} state={{ from: location }} replace />
  }

  // If the user is authenticated, they get to the route
  return <Outlet />
}

Wrap component need to be protected within ProtectRoute

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <PrivateRoute unauthenticatedPath="home" roles={['admin']}>
      <Route path="/dashboard" element={<Dashboard />} />
    </PrivateRoute>
  </Routes>
</BrowserRouter>
nart
  • 1,508
  • 2
  • 11
  • 24
  • `ProtectRoute` should be `ProtectedRoute`, however in the snippet you're calling it `PrivateRoute`. The `useCallback` should be a `useMemo` since you need only a boolean value. – timotgl Apr 06 '22 at 10:21