|
// 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')); |