Created
July 1, 2019 20:26
-
-
Save 197291/2b462f37433ead13a17cc2b93bbc2e33 to your computer and use it in GitHub Desktop.
Auth HOC, React.js
This file contains 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
// Test every passed-in auth verification function. | |
const verifyAuth = (authCriteria, props) => { | |
if (authCriteria.length === 0) return true; | |
return authCriteria.every(criterion => criterion(props)); | |
}; | |
// Authentication HoC | |
const withAuth = ({ | |
authCriteria = [], | |
redirectPath = '/', | |
} = {}) => Component => props => { | |
const isAuthorized = verifyAuth(authCriteria, props); | |
return ( | |
isAuthorized ? ( | |
<Component {...props} /> | |
) : ( | |
<Redirect | |
to={{ | |
pathname: redirectPath, | |
state: { from: props.location }, | |
}} | |
/> | |
) | |
); | |
}; | |
// TODO: authenticate user | |
const validUser = _props => true; | |
// The next route must have been referred by a previous route | |
const internalReferral = props => defined(props.location.state); | |
// The Store route has different authentication requirements | |
// than the other two routes | |
const storeCriteria = [validUser]; | |
const mainCriteria = [validUser, internalReferral]; | |
const authRoute = withAuth({ authCriteria: mainCriteria }); | |
const ProtectedRoutes = { | |
Store: withAuth({ authCriteria: storeCriteria })(Store), | |
Shipping: authRoute(Shipping), | |
Checkout: authRoute(Checkout), | |
}; | |
const AppRouter = () => { | |
return ( | |
<Router> | |
<Switch> | |
<Route exact path='/' component={ProtectedRoutes.Store} /> | |
<Route exact path='/shipping' component={ProtectedRoutes.Shipping} /> | |
<Route exact path='/checkout' component={ProtectedRoutes.Checkout} /> | |
<Route render={() => (<h2>Not Found</h2>)} /> | |
</Switch> | |
</Router> | |
); | |
}; |
where do you import Redirect from?
probably react-router-dom
where do you import Redirect from?
react-router-dom.
Sorry, didn't see the message.
where do you import Redirect from?
probably react-router-dom
You absolutely right.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
where do you import Redirect from?