Instead of using [AuthGuard], I recommend renaming it to [AuthorizeGuard] as you are working with application user roles.
You can implement something similar to the following code snippet:
import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthorizationService } from './authorization.service';
@Injectable({
providedIn: 'root'
})
export class AuthorizeGuard implements CanActivateChild {
constructor(private authorizeService: AuthorizationService, private router: Router) {
}
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (this.hasPermissions(route.data.roles)) {
return true;
} else {
this.router.navigate(['/']);
}
}
private hasPermissions(allowedRoles: string[]): boolean {
const idxArray: number[] = [];
allowedRoles.forEach((role: string) => {
const idx: number = this.authorizeService.permissions.indexOf(role);
if (idx !== -1) {
idxArray.push(idx);
}
});
if (idxArray.length > 0) {
return true;
} else {
return false;
}
}
}
AuthorizationService is used to retrieve the login user permissions from an API in my case, it's an array list.
If the login user does not have the required permission from the array, it will return false.