nikagar4
nikagar4

Reputation: 840

Angular 2 router canActivate Auth Guard

I've been searching for this for last 4 hours and couldn't find any answers.

I have several Authguards written, and i want to be able to tell router that if some of them are true it should give permission, but angular 2 router checks if every guard is true and then gives permission, otherwise it will block the link, is there any good way of doing this? i could write several Authentication guards but i don't think thats a good idea.

for example i want the /profile page to be accessible by admin and super-user, but i don't want the regular-user to access /profile page

Upvotes: 0

Views: 1492

Answers (2)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37343

You can inject your guards in one parent Guard and take the control yourself:

    @Injectable()
    class Guard implements CanActivate {

      constructor(private guard1: Guard1, private guard2: Guard2) {}

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean {
        // I'm assuming that your guard1.canActivate and guard2.canActivate return boolean
        return guard1.canActivate() || guard2.canActivate();
      }
    }

In your route config use only Guard guard:

{
  path : 'route',
  canActivate : Guard 
  ...
}

and of course you can use guard1 and guard2 in other routes.

Upvotes: 1

ulubeyn
ulubeyn

Reputation: 3021

You can use CanLoad interface in your authentication guard. For example let's say your route is just like that;

{
     path: 'profile',
     component: 'ProfileComponent',
     canLoad: [
          AuthenticationGuard
     ]
}

In your AuthenticationGuard, implement CanLoad interface. If user has no permission for this link, modules for this route would not be loaded.

export class AuthenticationGuard implements CanLoad {
     canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
          //in here ask your authentication service to check current user has permission for this route
     }
}

I hope it helps, please let me know for further questions.

Upvotes: 1

Related Questions