Moving Parameters in Guard Angular 2

advertisements

I have an app that I have setup with an Authentication Guard to make sure users cannot access the app unless they have logged in, like so

import { Injectable } from '@angular/core';
import {
    CanActivate, Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot,
    CanActivateChild } from '@angular/router';
import { AuthContext } from './auth-context.service';

@Injectable()
export class AuthGuard implements CanActivate {
        constructor(private router: Router, private authContext: AuthContext) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // Check to see if a user has a valid JWT
        if (this.authContext.userInfo !== undefined && this.authContext.userInfo.isAuthenticated) {
            // If they do, return true and allow the user to load the home component
            return true;
        }

        // If not, they redirect them to the login page
        this.router.navigate(['/login']);
        return false;
    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }
}

I want to add another guard for Authorization that will check if the user is in a certain role. Currently I am hiding the link in navigation based on this role.

 <div *ngIf="userInRole('Admin')">
             This is secret stuff
 </div>

But if a user knows a route, they can just plug it into the url. How would I add my "userInRole()" type functionality to a Guard? I would have to pass the role name and do the check in code. Do Guards support params?


A guard is just a class that implements CanActivate or CanDeactivate. But nothing stops you from injecting a service (or a value) that would return you the role of the user. For example,

export class AuthGuard implements CanActivate {
        constructor(private router: Router, private authContext: AuthContext,
             private user: MyUserService) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
          if (!this.user.isAdmin()) return false;
          ...

    }
}