How to implement Role based restrictions/permissions in react redux app?

前端 未结 5 2135
醉梦人生
醉梦人生 2021-02-06 12:18

I have a React-Redux-KoaJs application with multiple components. I have few user roles as well. Now i want to display few buttons, tables and div to only specific roles and hide

5条回答
  •  情话喂你
    2021-02-06 12:54

    I have implemented this in this rbac-react-redux-aspnetcore repository. If someone wants to use Redux with Context API, then the below code snippet can be helpful.

    export const SecuedLink = ({ resource, text, url }) => {
    
      const userContext = useSelector(state => {
        return state.userContext;
      });    
    
      const isAllowed = checkPermission(resource, userContext);
      const isDisabled = checkIsDisabled(resource, userContext);
    
      return (isAllowed &&  url}>{text})
    }
    
    
    const getElement = (resource, userContext) => {
        return userContext.resources
            && userContext.resources.length > 0
            && userContext.resources.find(element => element.name === resource);
    }
    
    export const checkPermission = (resource, userContext) => {
        const element = getElement(resource, userContext);
        return userContext.isAuthenticated && element != null && element.isAllowed;
    }
    
    export const checkIsDisabled = (resource, userContext) => {
        const element = getElement(resource, userContext);
        return userContext.isAuthenticated && element != null && element.isDisabled;
    }
    

    To use the above snippet, we can use it like below

      
      
    

    So, depending on the role, you can not only show/hide the element, but also can enable/disable them as well. The permission management is fully decoupled from the react-client and managed in database so that you don't have to deploy the code again and again just to support new roles and new permissions.

提交回复
热议问题