Skip to content

Instantly share code, notes, and snippets.

@FSou1
Created February 25, 2020 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FSou1/9058a464bceca1f8504f2be860668e3a to your computer and use it in GitHub Desktop.
Save FSou1/9058a464bceca1f8504f2be860668e3a to your computer and use it in GitHub Desktop.
import { CanActivate, CanLoad } from '@angular/router';
import { Router, ActivatedRouteSnapshot, Route } from '@angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { AuthService } from './services/auth.service';
import { Role } from './models/role';
@Injectable()
export class AuthGuard implements CanActivate, CanLoad {
constructor(
private router: Router,
private authService: AuthService
) { }
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | Promise<boolean> | boolean {
if (!this.authService.isAuthorized()) {
this.router.navigate(['login']);
return false;
}
const roles = route.data.roles as Role[];
if (roles && !roles.some(r => this.authService.hasRole(r))) {
this.router.navigate(['error', 'not-found']);
return false;
}
return true;
}
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
if (!this.authService.isAuthorized()) {
return false;
}
const roles = route.data && route.data.roles as Role[];
if (roles && !roles.some(r => this.authService.hasRole(r))) {
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment