From be154db913a14489b753db7cb92af08aa1411337 Mon Sep 17 00:00:00 2001 From: samau3 Date: Thu, 19 Sep 2024 17:21:49 -0700 Subject: [PATCH] Add role based rerouting logic --- client/src/App.jsx | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/client/src/App.jsx b/client/src/App.jsx index 986c19a7..d4567c9a 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -16,7 +16,7 @@ import Login from './pages/auth/login/login'; import Register from './pages/auth/register/register'; import Dashboard from './pages/dashboard/dashboard'; import AdminPatientsGenerate from './pages/admin/patients/AdminPatientsGenerate'; -import PatientNotFound from './pages/patients/notFound/PatientNotFound'; +import NotFound from './pages/notFound/NotFound'; import { AdminUsers } from './pages/admin/users/AdminUsers'; import Context from './Context'; @@ -65,6 +65,9 @@ Redirect.propTypes = RedirectProps; const ProtectedRouteProps = { role: PropTypes.string.isRequired, + restrictedRoles: PropTypes.arrayOf(PropTypes.string).isRequired, + destination: PropTypes.string, + message: PropTypes.string, children: PropTypes.element.isRequired, }; @@ -73,18 +76,30 @@ const ProtectedRouteProps = { * @param {PropTypes.InferProps} props * @returns {React.ReactElement} */ -function ProtectedRoute({ role, children }) { +function ProtectedRoute({ + restrictedRoles, + role, + destination = 'notFound', + message, + children, +}) { const navigate = useNavigate(); useEffect(() => { - if (role === 'FIRST_RESPONDER') { - navigate('/patients/not-found', { - replace: true, - state: { fromRedirect: true }, - }); + if (restrictedRoles.includes(role)) { + if (destination === 'forbidden') { + navigate('/forbidden', { + replace: true, + }); + } else { + navigate('/not-found', { + replace: true, + state: { message }, + }); + } } - }, [role, navigate]); + }, [restrictedRoles, role, navigate, destination, message]); - return role === 'FIRST_RESPONDER' ? : children; + return restrictedRoles.includes(role) ? : children; } ProtectedRoute.propTypes = ProtectedRouteProps; @@ -129,18 +144,23 @@ function App() { + } /> - } /> + } /> } /> } /> + } />