Skip to content

Instantly share code, notes, and snippets.

@L3V147H4N
Last active March 17, 2017 18:28
Show Gist options
  • Save L3V147H4N/92459ab9a9258b287a94714590d4bdc3 to your computer and use it in GitHub Desktop.
Save L3V147H4N/92459ab9a9258b287a94714590d4bdc3 to your computer and use it in GitHub Desktop.
React Role Based Component
import React from 'react';
import {
connect
} from 'react-redux';
import _ from 'lodash';
const Authorize = (allowedRoles) => {
return (WrappedComponent) => {
class WithAuthorization extends React.Component {
constructor (props) {
super(props);
}
render () {
let roles = [];
// this depends on how the roles are stored
if (this.props.auth.user && this.props.auth.user.Roles.length) {
roles = this.props.auth.user.Roles.map(r => r.name);
}
if (_.intersection(allowedRoles, roles).length) {
let props = {
...this.props
};
delete props.auth;
delete props.dispatch;
return <WrappedComponent {...props} />;
} else {
return null;
}
}
}
const mapStateToProps = (state) => {
return {
// .asMutable if you are using seamless-immutable
auth: state.authentication.asMutable({ deep: true })
};
};
return connect(mapStateToProps)(WithAuthorization);
};
};
export default Authorize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment