So im implementing a rbac in my code so i use laravel and react for this project i'm having problem so for context my role_id has label of like this
now i implement it using a RequireAuth.jsx so it has this code
import { useLocation,Navigate, Outlet} from 'react-router-dom';
import useAuth from '../hooks/useAuth';
const RequireAuth = ({ allowedRoles }) => {
const { auth } = useAuth();
const location = useLocation();
const userRole = auth?.role_id;
// Check if the user's role matches any of the allowed roles
const isAllowed = allowedRoles?.includes(userRole);
return (
isAllowed ? (
<Outlet />
) : (
auth?.user ? (
<Navigate to={{ pathname: '/unauthorized', state: { from: location } }} replace />
) : (
<Navigate to={{ pathname: '/login', state: { from: location } }} replace />
)
)
);
}
export default RequireAuth;
and my app.jsx has the allowedRoles being use for calling the role_id this is my App.jsx
function App() {
return (
<Routes>
{/* Public Route */}
<Route path="login" element={<Login/>}/>
<Route path='*' element={<NotFound/>}/>
<Route path='unauthorized' element={<Unauthorized/>}/>
<Route path="create" element={<Create/>}/>
<Route path="ask" element={<Ask/>}/>
{/* Protected Route */}
<Route element={<RequireAuth allowedRoles={[1]}/>}>
<Route path="/" element={<Dashboard/>}/>
<Route path="notification" element={<Notification/>}/>
<Route path="user" element={<User/>}/>
<Route path="scholar" element={<Scholar/>}/>
<Route path="scholarship" element={<Scholarship/>}/>
<Route path="submission" element={<Submission/>}/>
<Route path="export" element={<Export/>}/>
<Route path="school" element={<School/>}/>
<Route path="view" element={<ViewSubmission/>}/>
</Route>
{/* Manager Route */}
<Route element={<RequireAuth allowedRoles={[2]}/>}>
<Route path="scholar" element={<Scholar/>}/>
</Route>
{/* Scholar Route */}
<Route element={<RequireAuth allowedRoles={[3]}/>}>
<Route path="scholar-dashboard" element={<ScholarDashboard/>}/>
<Route path="scholar-submission" element={<ScholarSubmission/>}/>
<Route path="scholar-profile" element={<ScholarProfile/>}/>
</Route>
</Routes>
)
}
export default App
so my main problem here is when i login using my admin account it works but when i try to login thru the manager and scholar it return unauthorized navigate from my requireauth.jsx and another goal is the scholar cant access some of the tabs of the admin
i just change my onsubmit with a navigate of every roles so i created a ternary operation to pass on it basing on the route they should have
const rolePath = role_id === 1 ? '/' : role_id === 2 ? '/' : role_id === 3 ? '/scholar-dashboard' : '/login';
// Navigate the user to the intended route (from variable contains the intended route)
navigate(rolePath);