Skip to content

Instantly share code, notes, and snippets.

@minhchu
Created November 28, 2018 06:57
Show Gist options
  • Save minhchu/8c7eead4be6654ccc742c73c30e50d4b to your computer and use it in GitHub Desktop.
Save minhchu/8c7eead4be6654ccc742c73c30e50d4b to your computer and use it in GitHub Desktop.
React Role Based Authorization
const User = Authorization(['user', 'manager', 'admin'])
const Manager = Authorization(['manager', 'admin'])
const Admin = Authorization(['admin'])
const UserPage = User(Users)
const EditUserPage = Manager(EditUser)
const CreateUserPage = Admin(CreateUser)
<Router history={BrowserHistory}>
<Route path="/" component={App}>
<Route path="users" component={UserPage}>
<Route path=":id/edit" component={EditUserPage} />
<Route path="create" component={CreateUserPage} />
</Route>
</Route>
</Router>
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
/**
* HOC that Handles whether or not the user is allowed to see the page.
* @param {array} allowedRoles - user roles that are allowed to see the page.
* @returns {Component}
*/
export default function Authorization(allowedRoles) {
return WrappedComponent => {
class WithAuthorization extends Component {
static propTypes = {
user: PropTypes.object,
};
constructor(props) {
super(props);
}
render() {
const { user } = this.props;
if (allowedRoles.includes(user.account_type)) {
return <WrappedComponent {...this.props} />;
} else {
return <h1>No page for you!</h1>;
}
}
};
return connect(state => {
return { user: state.application.user };
})(WithAuthorization);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment