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

前端 未结 5 2125
醉梦人生
醉梦人生 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:57

    So, I have figured out there is an alternate and easy approach to implement role based access (RBAC) on frontend.

    In your redux store state, create a object called permissions (or you can name it whatever you like) like this:

    const InitialState = {
      permissions: {}
    };
    

    Then on your login action, setup the permissions that you want to provide like this:

    InitialState['permissions'] ={
      canViewProfile: (role!=='visitor'),
      canDeleteUser: (role === 'coordinator' || role === 'admin')
      // Add more permissions as you like
    }
    

    In the first permission you are saying that you can view profile if you are not a visitor. In the second permission you are saying that you can delete a user only if you are an admin or a coordinator. and these variables will hold either true or false on the basis of the role of the logged in user. So in your store state u will have a permission object with keys that represent permissions and their value will be decided on the basis of what your role is.

    Then in your component use the store state to get the permission object. You can do this using connect like:

    const mapStateToProps = (state) => {
      permissions : state.permissions
    }
    

    and then connect these props to your Component like:

    export default connect(mapStateToProps,null)(ComponentName);
    

    Then you can use these props inside your component on any particular element which you want to show conditionally like this:

    {(this.props.permissions.canDeleteUser) && }
    

    The above code will make sure that the delete user button is rendered only if you have permissions to delete user i.e. in your store state permissions object, the value of canDeleteUser is true.

    That's it, you have appplied a role based access. You can use this approach as it is easily scalable and mutable, since you will have all permsisions according to roles at one place.

    Hope, this helps! If i missed out something please help me in the comments. :-)

提交回复
热议问题