frontarm / navi

🧭 Declarative, asynchronous routing for React.
https://frontarm.com/navi/
MIT License
2.07k stars 71 forks source link

How to use authenticated routes that are permission based? #112

Closed maliiiith closed 5 years ago

maliiiith commented 5 years ago

I'm trying out Navi on a ReactJS application that has a bit complex routing system. What I'm doing right now is having a wildcard route, and then do necessary permissions checks and then mount routes based on the checks.

'*': map((request, context) => {
    const { authService, } = context;
    if(_.isEmpty(authService.currentUser)){
      const originalUrl = encodeURIComponent(request.originalUrl);
      return redirect(
        `${routeRegistry.login.path}?redirectTo=${originalUrl}`,
        {exact: false,}
      )
    }
    if(!authService.currentUser.name) {
      return getLoginRoutes();
    }
    return getAuthenticatedRoutes();
  })
const getAuthenticatedRoutes = () => {
  return mount({
    [routeRegistry.dashboard.path]: ...
  })
};
const getLoginRoutes = () => {
  return mount({
    '/': ...
  })
};

But with this approach I'm unable to unmount routes if the user loses permissions (when logging out).

Do you have an example similar to what I'm trying to do right now?

jamesknelson commented 5 years ago

You’re on the right track! I do something similar in my current app. The main difference in my approach is I pass the currentUser to context, and call navigation.setContext to update it when it changes (which recomputes the routes).

Let me know if this helps.

vongohren commented 5 years ago

@jamesknelson that is interesting. Will the routes that earlier was mounted, be unmounted? Or what happens at setContext? Is it that of 'restting' the routes as you explain in the documentation of not trying to change the context to often?

jamesknelson commented 5 years ago

Changing the context will just recompute the route object from scratch. You can think of this as calling a setState within the <Router> function - it can be very fast, or quite slow depending on the size and design of your application.

In any case, authentication state changing should be a relatively rare event, so it shouldn't be a problem to call setState when auth state changes.

vongohren commented 5 years ago

@jamesknelson cool cool thanks! Is there a difference from setContext, and changing the object that is sent in to the context of the router? As you mention here: https://frontarm.com/navi/en/guides/routing-context/#the-context-prop that if the object changes a new computation changes.

jamesknelson commented 5 years ago

They're actually the same thing. Changing the context prop just calls setContext under the hood.

vongohren commented 5 years ago

Kkk, then I understand more :) Thanks. I will let @malithrw close this when he is done with examples and understood it himself

maliiiith commented 5 years ago

Thanks guys!