Skip to content

Instantly share code, notes, and snippets.

@stenno
Last active February 4, 2020 13:07
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 stenno/297b7a7560d0ef754eb0b7256750511a to your computer and use it in GitHub Desktop.
Save stenno/297b7a7560d0ef754eb0b7256750511a to your computer and use it in GitHub Desktop.
Enabling routes with Role-based auth
/* 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>
);
}
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;
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