Skip to content

Instantly share code, notes, and snippets.

@ScriptBytes
Created January 18, 2020 22:32
Show Gist options
  • Save ScriptBytes/fd6b5129e8d466e21ab4631773099142 to your computer and use it in GitHub Desktop.
Save ScriptBytes/fd6b5129e8d466e21ab4631773099142 to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../auth.service';
@Injectable({
providedIn: 'root'
})
export class HasRoleGuard implements CanActivate {
constructor(
private authService: AuthService,
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const role = next.data.role;
const user = this.authService.user();
const idx = user.roles.findIndex(r => r === role);
if (idx >= 0) {
return true;
}
return this.router.createUrlTree(['unauthorized']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment