125. Creating Guard (#15)

This commit is contained in:
Art
2021-09-17 10:05:16 +03:00
parent 5d0eae9a3c
commit 2fb286ac00
2 changed files with 19 additions and 3 deletions

View File

@ -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;
}
}
}

View File

@ -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;