I have a router configuration with multiple routes and sub-routes. If the user is unauthorized, i need to redirect him to authorization page from all the pages except one. My basic configuration is something like this
</Route>
<Route path = "auth" handler = {Auth}/>
<Route handler = {App}>
<Route handler = {Container}>
<Route path = "page1" handler = {Page1}/>
<Route path = "page2" handler = {Page2}/>
<Route path = "page3" handler = {Page3}/>
</Route>
</Route>
</Route>
I need to redirect the user if to /auth if he is unauthorized, but i need to let the user access page2
Adopting the auth-flow solution to your routes:
Somewhere in your application, whether its in redux state or a global variable or API singleton, you'll have a value indicating whether the user is authorized, which is what auth refers to in this example. Define an onEnter handler for routes that need authentication:
function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/login',
state: { nextPathname: nextState.location.pathname }
})
}
}
and then use it on the routes you need to check
<Route>
<Route path = "auth" handler = {Auth}/>
<Route handler = {App}>
<Route handler = {Container}>
<Route path = "page1" handler = {Page1}/>
<Route path = "page2" handler = {Page2}/>
<Route path = "page3" handler = {Page3} onEnter = { requireAuth } />
</Route>
</Route>
</Route>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With