Skip to content

Instantly share code, notes, and snippets.

@197291
Created July 1, 2019 20:26
Show Gist options
  • Save 197291/2b462f37433ead13a17cc2b93bbc2e33 to your computer and use it in GitHub Desktop.
Save 197291/2b462f37433ead13a17cc2b93bbc2e33 to your computer and use it in GitHub Desktop.
Auth HOC, React.js
// 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>
);
};
@CWarth93
Copy link

where do you import Redirect from?

@DarkoTrpevski
Copy link

where do you import Redirect from?

probably react-router-dom

@197291
Copy link
Author

197291 commented Nov 20, 2020

where do you import Redirect from?

react-router-dom.
Sorry, didn't see the message.

@197291
Copy link
Author

197291 commented Nov 20, 2020

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