Created
January 18, 2020 22:32
-
-
Save ScriptBytes/fd6b5129e8d466e21ab4631773099142 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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