Skip to content

Instantly share code, notes, and snippets.

@lomteslie
Created August 24, 2018 17:30
Show Gist options
  • Save lomteslie/5b9abfc29c076e50cd2ab6ea31f771ca to your computer and use it in GitHub Desktop.
Save lomteslie/5b9abfc29c076e50cd2ab6ea31f771ca to your computer and use it in GitHub Desktop.
RestrictedRoute.js
import PropTypes from 'prop-types';
import React from 'react';
import { hasFeature, hasPermission } from 'lib/auth';
import { Route, Redirect } from 'react-router-dom';
class RestrictedRoute extends React.Component {
static propTypes = {
component: PropTypes.func,
features: PropTypes.array,
permissions: PropTypes.array
};
state = { isAuthorized: false };
componentDidMount() {
const { features = [], permissions = [] } = this.props;
let isAuthorized = false;
if (features.length && permissions.length) {
isAuthorized = hasFeature(features) && hasPermission(permissions);
} else if (features.length) {
isAuthorized = hasFeature(features);
} else if (permissions.length) {
isAuthorized = hasPermission(permissions);
}
console.log('Is auth? ', isAuthorized);
this.setState(state => {
console.log('STATE: ', state, isAuthorized);
if (state.isAuthorized === isAuthorized) {
return null;
}
return { isAuthorized };
});
}
render() {
const { component: Component, ...rest } = this.props;
console.log('hey rendering', this.state);
return (
<Route
{...rest}
render={props => {
console.log('oh hai')
if (this.state.isAuthorized) {
return <Component {...props} />;
}
return <Redirect to="/unauthorized" />;
}}
/>
);
}
}
export default RestrictedRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment