import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, ActivatedRoute } from '@angular/router'; import { PublicService } from '../PublicService'; import { JwtHelperService } from '@auth0/angular-jwt'; import { Constants } from '../Constant'; import { LoginService } from '../login/login.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { private exp; private token; private user; public constructor( private readonly router: Router, private readonly route: ActivatedRoute, private readonly publicService: PublicService, private readonly loginService: LoginService, private readonly jwt: JwtHelperService ) {} public canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): boolean { this.token = this.publicService.getToken(); this.user = this.publicService.getCurrentUser(); if (this.token) { this.exp = (this.jwt.decodeToken(this.publicService.getToken())).exp; const nowTime = new Date().getTime() / 1000; if (nowTime > this.exp){ if (this.user.userConfig.isAutoLogin === '1'){ this.loginService.login(this.user.userName, this.user.passWord).then(res => { if (res.code === Constants.SUCCESS){ this.publicService.setToken(res.data); } console.log(res); }); return true; }else{ return false; } }else{ return true; } }else{ this.router.navigate(['/login']); return false; } } }