Untitled

 avatar
unknown
plain_text
a year ago
2.3 kB
4
Indexable
// APP.JSX 
<Route element={<ProtectedPath allowedRoles={["Admin", "approver"]} />}>
          <Route path="UserManagement" element={<UserManagement />} />
          <Route
            path="UserManagement/CreateUser"
            element={<CreateEditUser />}
          />
          <Route path="UserManagement/EditUser" element={<CreateEditUser />} />
          <Route path="UserManagement/UploadUser" element={<UploadUser />} />
          <Route path="RoleManagement" element={<RoleManagement />} />
          <Route
            path="UserAuthorisationManagement"
            element={<UserAuthorisationManagement />}
          />
          <Route
            path="UserAuthorisationManagement/CreateNewUserAuthorization"
            element={<CreateNewUserAuthorization />}
          />
</Route>

// ProtectedPath.JSX 
import React from "react";
import { useLocation, Navigate, Outlet } from "react-router-dom";
/* --------------------------------- redux -------------------------------- */
import { useSelector } from "react-redux";
/* ---------------------------- api and constant ---------------------------- */

// Outlet is an extension of the routes pass in by the parent component used in React Router V6
/* -------------------------------------------------------------------------- */
/*                                 RequireAuth                                */
/* -------------------------------------------------------------------------- */
const ProtectedPath = ({ allowedRoles }) => {
  console.log("RequireAuth - render");

  const location = useLocation();
  const currentUserDetails = useSelector(
    (state) => state.workflowManager.getCurrentUserDetails
  );
  console.log(">>display current user details >>>", currentUserDetails.roleId);
  console.log(">>display allowed roles", allowedRoles);
  const currentUserRole = currentUserDetails.roleId;
  const userRoleIsAllowed = allowedRoles.includes(currentUserRole);
  console.log(">> display is user allowed?", userRoleIsAllowed);
  return userRoleIsAllowed ? (
    <Outlet />
  ) : currentUserDetails.length > 0 ? (
    <Navigate to="unauthorised" state={{ from: location }} replace />
  ) : (
    <Navigate to="/qtech" state={{ from: location }} replace />
  );
};

export default ProtectedPath;