Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router configuration for unauthorised pages

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

like image 390
Ivan Avatar asked Dec 07 '25 23:12

Ivan


1 Answers

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>
like image 143
Nathan Hagen Avatar answered Dec 09 '25 15:12

Nathan Hagen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!