Skip to content

Instantly share code, notes, and snippets.

@tuanpht
Last active April 26, 2018 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuanpht/17412543eb1b7f330ef637d753d6ec07 to your computer and use it in GitHub Desktop.
Save tuanpht/17412543eb1b7f330ef637d753d6ec07 to your computer and use it in GitHub Desktop.
React HOC authentication, authorization
// Ref: https://hackernoon.com/role-based-authorization-in-react-c70bb7641db4
// Demo: https://codesandbox.io/s/n1n5jl374p
import React, { Fragment } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function getCurrentUser() {
// return null; // Not login
return {
id: 1,
name: 'Admin',
// role: "user", // User role
role: 'admin', // Admin role
};
}
function RequireAuthentication(WrappedComponent) {
return function(props) {
const user = getCurrentUser();
if (user) {
return <WrappedComponent {...props} />;
}
return <Login />;
};
}
function Authorization(allowedRoles) {
return function(WrappedComponent) {
return function(props) {
const { role } = getCurrentUser();
if (allowedRoles.includes(role)) {
return <WrappedComponent {...props} />;
}
return <h1>No page for you!</h1>;
};
};
}
function Login() {
return <h1>Please login</h1>;
}
function AdminRoute() {
return <h1>This is for Admin</h1>;
}
function Home() {
return <h1>This is home for all</h1>;
}
function App() {
const AdminRole = Authorization(['admin']);
const EditorRole = Authorization(['editor']);
const MyAdminRoute = RequireAuthentication(AdminRole(AdminRoute));
return (
<Router>
<Fragment>
<Route path="/" exact component={Home} />
<Route path="/admin" component={MyAdminRoute} />
</Fragment>
</Router>
);
}
render(<App />, document.getElementById('root'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment