125. Creating Guard (#15)
This commit is contained in:
@ -1,15 +1,31 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
|
||||
import {Observable} from 'rxjs';
|
||||
import {AuthenticationService} from "../service/authentication.service";
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthenticationGuard implements CanActivate {
|
||||
|
||||
constructor(private authenticationService: AuthenticationService, private router: Router) {
|
||||
}
|
||||
|
||||
canActivate(
|
||||
route: ActivatedRouteSnapshot,
|
||||
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
|
||||
return true;
|
||||
return this.isUserLoggedIn();
|
||||
}
|
||||
|
||||
private isUserLoggedIn(): boolean {
|
||||
if( this.authenticationService.isUserLoggedIn())
|
||||
return true;
|
||||
else {
|
||||
this.router.navigate(['/login']);
|
||||
|
||||
//todo - send notification to user
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -65,7 +65,7 @@ export class AuthenticationService {
|
||||
return this.token;
|
||||
}
|
||||
|
||||
public isLoggedIn(): boolean {
|
||||
public isUserLoggedIn(): boolean {
|
||||
this.loadToken();
|
||||
if (this.token != null && this.token !== '') {
|
||||
let subject = this.jwtHelper.decodeToken(this.token).sub;
|
||||
|
||||
Reference in New Issue
Block a user