I want to protect the routes and do the roles authorisation, and authentication in a react website. But I couldn’t find a fast way of doing it. I.e. Different buttons on the AppBar are hidden or shown based on the role of the user. But I couldn’t find anything that could help me achieve that apart from querying the database.

I’m protecting the routes currently using the roles authorisation, and authentication, which queries firebase database and firebase auth for the roles and the assigned user respectively.

1 Answers

0
Codesingh On

If you are using react-router-dom there is a component prop and the value pass to component prop is component wrapped with hoc. Below is the way to use it:-

<Route exact path="/yourpathhere" component={checkAllotedRoutes(yourComponent)} />
//In the above route component is basically a hook check.
export default function checkAllotedRoutes(Component) {
  class Permissions extends React.Component {
    static contextTypes = {
      location: PropTypes.object,
    };

    permissionAvailable = (locationKey) => {
     // see if location is there in permission array 
     return permissions.includes(locationKey);
    }

    componentWillMount() {
      this.permissionAvailable(this.props.location.key);
    }

    componentWillReceiveProps(nextProps) {
      // not 100% sure about using `locatoin.key` to distinguish between routes
      if (nextProps.location.key !== this.props.location.key) {
        this.permissionAvailable(nextProps.location.key);
      }
    }

    render() {
      return React.createElement(Component, { ...this.props });
    }
  }

  Permissions.propTypes = {
    location: PropTypes.object,
  };

  return Permissions;
}

In the above code the component is pass inside the hoc where we will check the permission.