If you’ve wondered how you can authorize a certain user role to see a React component this will come in handy 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);
},
};