Open Source: Authorize User Roles React Component


#1

If you’ve wondered how you can authorize a certain user role to see a React component this will come in handy :smiley: If the user goes to a page they’re not supposed to it will instead render a not authorized page. To correct the router url you can redirect with an optional action.

This is using the higher order function pattern to return a new function (component) that’s wrapped in the authorization component.

Note, the user can still find data in the browser with this component, make sure you only send down sensitive data with a secure subscription.

SecretsPage = React.createClass({
  render() {
    return (<div>Secrets: Foo Bar</div>);
  }
});

SecretsPage = `authorizeForRole(['admin', 'player'], SecretsPage);`

#### authRoles.js ```javascript // Require authorized user role before rendering // // roles: Array String, comp: Component, props: Maybe Object // returns Func Component authorizeForRole = function authorizeForRole(roles, comp, props) { const Authorizer = React.createClass({ componentDidMount() { const Auth = AuthorizeReactComponent;
  if (!userIsInRole(roles)) {
    if (typeof Auth.notAuthorizedAction === 'function') {
      Auth.notAuthorizedAction();
    }
  }
},

render() {
  const Component = comp;
  if (userIsInRole(roles)) {
    return (<Component {...props} />);
  }
  return (<AuthorizeReactComponent.notAutorizedComponent />);
},

});
return Authorizer;
};

// roles: Array String -> Bool
function userIsInRole(roles) {
return Roles.userIsInRole(Meteor.userId(), roles);
}



#### client/startup.js

```javascript

  AuthorizeReactComponent = {

    notAutorizedComponent: Comps.NotAuthorized,

    notAuthorizedAction:() => {
      setTimeout(goSomewhereElse, 1200);
    },
  };

#2

This is a very simple question as I’ve not yet touched React, but I’m curious: can you restrict access to only a single component, and display something like ‘login to see price’? Thanks!


#3

You should make sure that people don’t use this to actually hide secret data, because if it is loaded to the client at all then it can be found in the browser.

This is more like a useful way to display a nice message to people instead of a blank page when they aren’t authorized to see something.


#4

Ah yea good point @sashko ! My use case was to prevent them from accidentally going to the page, and if they do re-direct them. If they did hack it the publication would never send the sensitive data (much like hacking IronRouter with the Roles package).

I’ll make sure to add that to the docs!


[quote="ryandeussing, post:2, topic:9835, full:true"] This is a very simple question as I've not yet touched React, but I'm curious: can you restrict access to only a single component, and display something like 'login to see price'? Thanks! [/quote]

Yep the notAutorizedComponent config key accepts a React component like Login.