0

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

nikagar4
  • 830
  • 4
  • 11
  • 23
  • you can do that using guard as well for example check the coming user is admin, SU then return true otherwise false etc you can handle it logically – Babar Hussain Mar 16 '17 at 12:03

2 Answers2

1

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.

Roy
  • 7,811
  • 4
  • 24
  • 47
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
1

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.

ulubeyn
  • 2,761
  • 1
  • 18
  • 29