skip to Main Content

How can I implement role based access control here:

I have a useAuth hook that gets the logged in user role. I want some pages to be accessed only by the Admin. I tried to pass the allowedRoles prop to the Dashboard element but I haven’t quite figured it out yet.

import { Navigate, Route, Routes } from "react-router-dom";
import routes from "#routes";
import useAuth from "../hooks/useAuth";

export default function Dashboard() {

  const getRoute = () => {
    return window.location.pathname !== "/dashboard/full-screen-maps";
  };

  const getRoutes = (routes) => {
    return routes.map((prop, key) => {
      if (prop.layout === "/dashboard") {
        return <Route path={prop.path} element={prop.element} key={key} />;
      } else {
        return null;
      }
    });
  };

  return (
    <ChakraProvider theme={theme} resetCss={false}>
        {getRoute() ? (
              <Routes>
                {getRoutes(routes)}
                <Route
                  path="/dashboard"
                  element={<Navigate to="/dashboard/overview" />}
                />
                <Route path="*" element={<Navigate to="/auth/notfound" />} />
              </Routes>
        ) : null}
    </ChakraProvider>
  );
}

routes.jsx

import Overview from "./views/Overview ";
import Teams from "./views/Teams ";
import Apps from "./views/Apps ";

const dashRoutes = [
  {
    path: "/overview",
    element: <Overview />,
    layout: "/dashboard",
    allowedRoles: ["Admin"]
  },
  {
    path: "/teams",
    element: <Teams />,
    layout: "/dashboard",
    allowedRoles: ["Admin"]
  },
  {
    path: "/apps",
    element: <Apps />,
    layout: "/dashboard",
    allowedRoles: ["Admin", "Engineer"]
  },
]

useAuth.js

import { useSelector } from "react-redux";

const useAuth = () => {
  const { user } = useSelector((state) => state.auth);

  let Admin = false;
  let Engineer = false;
  let status = "Operations";

  if (user) {
    Admin = user?.payload?.role.includes("admin");
    Engineer = user?.payload?.role.includes("engineer");

    if (Admin) status = "admin";
    if (Engineer) status = "engineer";

    return { Admin, Engineer, status};
  }

  return { Admin, Engineer, status };
};
export default useAuth;

ChatGPT wasn’t much help

2

Answers


  1. If you are getting the user role permissions from the backend then there’s one possible solution.

    Steps:

    1. Get the user role and user permissions when you are getting the user details from backend.

    For Example: Let’s say we have two roles available:

    RoleConstants_Js

    1. Create a common RoleBasedRouting component, in that create a common function that check for the user role and redirects to the page if user has the permission.

    RoleBasedRouting_Js

    1. Wrap up the Html that need to be displayed by the RoleBaseRouting in App.js file, which will render the page if the user has permission.

    App_Js

    Login or Signup to reply.
  2. Check the current user’s role when mapping the dashboard routes.

    import { Navigate, Route, Routes } from "react-router-dom";
    import routes from "#routes";
    import useAuth from "../hooks/useAuth";
    
    export default function Dashboard() {
      const { status } = useAuth();
    
      const getRoute = () => {
        return window.location.pathname !== "/dashboard/full-screen-maps";
      };
    
      const getRoutes = (routes) => {
        return routes.map(({ layout, allowedRoles, ...props }, key) => {
          return layout === "/dashboard" && allowedRoles.includes(status)
            ? <Route key={key} {...props} />
            : null;
        });
      };
    
      return (
        <ChakraProvider theme={theme} resetCss={false}>
          {getRoute()
            ? (
              <Routes>
                {getRoutes(routes)}
                <Route
                  path="/dashboard"
                  element={<Navigate to="/dashboard/overview" />}
                />
                <Route path="*" element={<Navigate to="/auth/notfound" />} />
              </Routes>
            ) : null
          }
        </ChakraProvider>
      );
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search