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
If you are getting the user role permissions from the backend then there’s one possible solution.
Steps:
For Example: Let’s say we have two roles available:
RoleConstants_Js
RoleBasedRouting_Js
App_Js
Check the current user’s role when mapping the dashboard routes.