Created
August 24, 2018 17:30
-
-
Save lomteslie/5b9abfc29c076e50cd2ab6ea31f771ca to your computer and use it in GitHub Desktop.
RestrictedRoute.js
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 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