I want to implement RBAC in my React project and here I have different role Like ADMIN,SUPERADMIN etc. and I am storing that user role in LocalStorage and showing information according to the user role so what actually happening that if user is ADMIN that store in localStorage have only access to limited things but when he change its role to SuperAdmin from localstorage from dev or console he get all the access of SuperAdmin what I can do?
CodePudding user response:
You can Create one Middleware
so every route passed
or render
from that Middleware and It's a better way to you can use API's call in your middleware for checking the Roles.
Example :
PrivateRoute.tsx
import React, { useContext, useEffect } from 'react'
import { Redirect, Route } from 'react-router-dom'
export const PrivateRoute = props => {
// Get User info from local storage
const userData = localStorage.getItem('user')
const userRole = userData?.role;
useEffect(() => {
// do something here for async check
},[])
const hasPermission = useMemo(() => {
// some condition checks for roles access for perticluar module
return ...
}, [userRole]);
if (hasPermission) {
return <Route {...props} />
}
return <Redirect to={'Some Path'} />
};
CodePudding user response:
The fact is that handling this kind of authorization is not enough on the frontend side. You can ask your backend to give you whether the user is ADMIN or SUPERADMIN or whatever. Then you can store this authentication status in a state management, so you'd easily access that after.
For implementing different situations, You can use guard some routes or render components conditionally considering which type the user is.
In my opinion, HOCs
(wrapping the components with them) & conditional rendering
can help you with RBAC.