Search code examples
angularangular-ui-routerangular8auth-guardangular-route-guards

How can I allow routes to users based on module condition?


I know the usage of Auth guard in Angular and I am just a beginner in angular I just made a basic authentication based on read write access that includes roles like isAdmin or Isguest

But now I want that particular user must be able to access only some routes

Like I have three modules

  1. A component
  2. B component
  3. C component

And all the above components may be child or may not be child routes.

I want that harry user can access to module A and B

Jackson can access to module B and C

Michel can access module A only

So how to architect such type of mechanism in Angular?

Actually I know Auth guard but how can I organise the data like in database to add list of components or something etc etc?

What conditions must I need to add in canActivate ?

A solution by which I need to handle less and be dynamic if tommorrow a new component comes and I need to access grants.

Any great ideas are welcomed...!!


Solution

  • You can add permission for each route and store the permissions required for each user.

    const routes: Routes = [
      {
        path: 'dashboard',
        loadChildren: () => import('./dashboard/dashboard.module').then(mod => mod.DashboardModule),
        canActivate: [ Guard ],
        data: { permission: 'view dashboard' }
      }
    

    and inside canActivate() you can check if the permission is present in user data.

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if(!route.data || (route.data && this.user.permissions.find(route.data.permission))) {
        return true;
      }
    }