Last active
February 4, 2020 13:07
-
-
Save stenno/297b7a7560d0ef754eb0b7256750511a to your computer and use it in GitHub Desktop.
Enabling routes with Role-based auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Snippet */ | |
render() { | |
const { roles, username } = this.state; | |
const userObject = { username, roles }; | |
return ( | |
<UserContext.Provider value={ userObject }> | |
<Sidebar /> | |
<EnabledRoute name='dashboard' exact component={ Dashboard } /> | |
<EnabledRoute name='admin' exact component={ Admin } /> | |
<EnabledRoute name='units' exact component={ Units } /> | |
</UserContext.Provider> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext} from 'react'; | |
import { useRouteMatch } from 'react-router-dom'; | |
import UserContext from '../context/UserContext'; | |
import routes from './routes'; | |
const EnabledRoute = (props) => { | |
const { roles } = useContext(UserContext); | |
const { name, exact, component: Component } = props; | |
const { role, route: path } = routes.find(route => route.name === name); | |
const match = useRouteMatch({ path, exact }); | |
return match && roles.includes(role) && <Component />; | |
}; | |
export default EnabledRoute; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
const routes = [ | |
{ | |
name: 'admin', | |
label: 'Admin', | |
role: 'ROLE_ADMIN', | |
route: '/admin' | |
}, | |
{ | |
name: 'units', | |
label: 'Units', | |
role: 'ROLE_UNITS', | |
route: '/units' | |
} | |
]; | |
export default routes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment