Created
April 13, 2019 10:12
-
-
Save BigBadJock/b1baadf6ff431a71db8edf06ac8a48ce to your computer and use it in GitHub Desktop.
Angular 7 Authentication Guard Service
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 { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot } from '@angular/router'; | |
import { Observable } from 'rxjs'; | |
import { AuthenticationService } from 'src/app/Services/Authentication/authentication.service'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class AuthGuard implements CanActivate, CanLoad { | |
constructor(private authService: AuthenticationService, private router: Router) { } | |
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): | |
Observable<boolean> | Promise<boolean> | boolean { | |
if(! state || ! state.url) return false; | |
let isValid: boolean = this.checkLoggedIn(state.url); | |
if (isValid) { | |
if (route.data && route.data.expectedClaim) { | |
let expectedClaim = route.data.expectedClaim; | |
isValid = this.checkClaim(expectedClaim); | |
} | |
} | |
return isValid; | |
} | |
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean { | |
if(! route || ! route.path) return false; | |
let isValid: boolean = this.checkLoggedIn(route.path); | |
if (isValid) { | |
if (route.data && route.data.expectedClaim) { | |
let expectedClaim = route.data.expectedClaim; | |
isValid = this.checkClaim(expectedClaim); | |
} | |
} | |
return isValid; | |
} | |
checkLoggedIn(url: string): boolean { | |
if(this.authService.checkLoggedIn()) { | |
return true; | |
} | |
this.authService.redirectUrl = url; | |
this.router.navigate(['/authentication/login']); | |
return false; | |
} | |
checkClaim(claim: string) { | |
let hasClaim: boolean = false; | |
if (this.authService.currentUser) { | |
hasClaim = this.authService.currentUser.claims.indexOf(claim) > -1; | |
} | |
return hasClaim; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment