Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 those from others. Please remember i dont want to hide the whole component, but just a part of the components. Can anyone help me? Thanks in advance.

like image 573
Harshit Agarwal Avatar asked May 06 '19 11:05

Harshit Agarwal


2 Answers

You can check the role or permission in every component as @Eudald Arranz proposed. Or you can write a component that will checks permissions for you. For example:

import PropTypes from 'prop-types';
import { connect } from 'react-redux';

const ShowForPermissionComponent = (props) => {
    const couldShow = props.userPermissions.includes(props.permission);
    return couldShow ? props.children : null;
};

ShowForPermissionComponent.propTypes = {
    permission: PropTypes.string.isRequired,
    userPermissions: PropTypes.array.isRequired
};


const mapStateToProps = state => ({
    userPermissions: state.user.permission //<--- here you will get permissions for your user from Redux store
});

export const ShowForPermission = connect(mapStateToProps)(ShowForPermissionComponent);

and then you can use this component like this:

import React from 'react';
import { ShowForPermission } from './ShowForPermission';

cons MyComponent = props => {
   return (
        <div>
            <ShowForPermission permission="DELETE">
                <button>Delete</button>
            </ShowForPermission>
        </div>
   );
}

like image 66
Andrii Golubenko Avatar answered Sep 18 '22 21:09

Andrii Golubenko


Be careful with that. If the actions of some roles are important you should always validate them at your backend. It's easy to change the values stored in redux at frontend allowing malicious use of the roles if there is no proper validation.

If you want to proceed on a possible approach is this:

  • Save the roles at your reducer
  • Bind the reducer to the component:
function mapStateToProps(state) {
  const { user_roles } = state;
  return { user_roles };
}

export default connect(mapStateToProps)(YourComponent);
  • Then at your component, you can check the user_roles and render the actions accordingly:
render() {
    return (
      <div>
        {this.props.user_roles.role === "YOUR_ROLE_TO_CHECK" && <ActionsComponent />}
      </div>
    );
  }

This will render the ActionsComponent only when the role is equal to the desired one.

Again, always validate the roles at your backend!

like image 32
Eudald Arranz Avatar answered Sep 21 '22 21:09

Eudald Arranz