Routing and Navigation
In our frontend application, we use React Router for handling routing and navigation. React Router is a popular routing library for React applications that provides declarative routing capabilities.
Installation
To install React Router Dom, you can use npm or yarn:
_10npm install react-router-dom_10_10or_10_10yarn add react-router-dom
Building our Role-based access component
To build our Role-based access component, we’ll follow this process;
-
When an employee signs in, the employee’s role and JWT token are stored in the Auth state.
-
When this employee requests access to a protected route, our role-based access component will access the Auth state and retrieve the employee’s role.
-
The employee’s role will then be cross-checked with an array containing the required roles for that route.
-
If the user’s role matches the required role, access is granted, else access will be denied.
Here’s the code for this;
_20import { useLocation, Navigate, Outlet } from "react-router-dom";_20import { useContext } from "react";_20import AuthContext from "../Context/authProvider";_20_20import React from "react";_20_20const Auth = ({ allowedRoles }) => {_20 const { auth } = useContext(AuthContext);_20 const location = useLocation();_20_20 return allowedRoles.find((role) => auth.role.includes(role)) ? (_20 <Outlet />_20 ) : auth?.name ? (_20 <Navigate to="/unauthorized" state={{ from: location }} replace />_20 ) : (_20 <Navigate to="/register" state={{ from: location }} replace />_20 );_20};_20_20export default Auth;
With this done, we’ll wrap each protected route with this component and pass to this component the required role for each page;
_30import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';_30import Home from './components/Home';_30import About from './components/About';_30import Contact from './components/Contact';_30import NotFound from './components/NotFound';_30_30const App = () => {_30 return (_30 <Routes>_30 <Route path="/" element={<Layout />}>_30 <Route path="/linkpage" element={<LinkPage />} />_30 <Route path="/register" element={<Register />} />_30 <Route path="/signin" element={<Signin />} />_30 <Route path="/unauthorized" element={<Unauthorized />} />_30 <Route path="/home" element={<Home />} />_30 <Route element={<Auth allowedRoles={["marketer"]} />}>_30 <Route path="/marketers-only" element={<MarketersPage />} />_30 </Route>_30 <Route element={<Auth allowedRoles={["se"]} />}>_30 <Route path="/se-only" element={<SEPage />} />_30 </Route>_30 <Route element={<Auth allowedRoles={["se"]} />}>_30 <Route path="/hr-Only" element={<HRPage />} />_30 </Route>_30 </Route>_30</Routes>;_30 );_30};_30_30export default App;
With these done, every group has access to only their specific route.