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

2k Views Asked by At

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...!!

2

There are 2 best solutions below

4
On BEST ANSWER

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;
  }
}

1
On

You will need to create an Auth Guard which will look like the following:

@Injectable()
    export class MyGuard implements CanActivate {
      constructor(private _myUserService: MyUserService) {}
    
      canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if(//ADD CONDITION HERE)
            return true;
        return false;
      }
    }

and then in your routes you will have something like:

{
    path: 'XXX',
    component: XXXComponent,
    canActivate: [MyGuard],
}