2 changed files with 68 additions and 19 deletions
@ -1,31 +1,70 @@ |
|||||||
import { Injectable } from '@angular/core'; |
import { HttpClient } from "@angular/common/http"; |
||||||
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; |
import { Injectable } from "@angular/core"; |
||||||
|
import { |
||||||
|
CanActivate, |
||||||
|
ActivatedRouteSnapshot, |
||||||
|
RouterStateSnapshot, |
||||||
|
Router, |
||||||
|
} from "@angular/router"; |
||||||
|
|
||||||
@Injectable({ |
@Injectable({ |
||||||
providedIn: 'root' |
providedIn: "root", |
||||||
}) |
}) |
||||||
export class AuthGuard implements CanActivate { |
export class AuthGuard implements CanActivate { |
||||||
|
constructor(private http: HttpClient, private router: Router) {} |
||||||
|
|
||||||
constructor(private router: Router) { |
// 路由守卫
|
||||||
|
async canActivate( |
||||||
|
next: ActivatedRouteSnapshot, |
||||||
|
state: RouterStateSnapshot |
||||||
|
): Promise<boolean> { |
||||||
|
console.log("next", next); |
||||||
|
console.log("state", state); |
||||||
|
|
||||||
|
if ( |
||||||
|
next.queryParams.singleSignOn && |
||||||
|
next.queryParams.singleSignOn === "true" |
||||||
|
) { |
||||||
|
//执行自动登录逻辑
|
||||||
|
await this.onSubmit(); |
||||||
} |
} |
||||||
|
return this.checkLogin(); |
||||||
|
} |
||||||
|
|
||||||
// 路由守卫
|
checkLogin(): boolean { |
||||||
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { |
// 判断本地有没有token
|
||||||
|
const token = sessionStorage.getItem("token"); |
||||||
|
|
||||||
return this.checkLogin(); |
// 如果有token,允许访问
|
||||||
|
if (token) { |
||||||
|
return true; |
||||||
} |
} |
||||||
|
|
||||||
checkLogin(): boolean { |
//如果没有token,跳转登录页
|
||||||
|
this.router.navigate(["/login"]); |
||||||
|
return false; |
||||||
|
} |
||||||
|
|
||||||
// 判断本地有没有token
|
onSubmit() { |
||||||
const token = sessionStorage.getItem('token'); |
return new Promise<void>((resolve, reject) => { |
||||||
|
this.http |
||||||
// 如果有token,允许访问
|
.post("/api/Account/SignIn", { |
||||||
if (token) { return true; } |
name: "superadmin", |
||||||
|
password: "SHya119!@", |
||||||
//如果没有token,跳转登录页
|
}) |
||||||
this.router.navigate(['/login']); |
.subscribe( |
||||||
return false; |
(data: any) => { |
||||||
} |
sessionStorage.setItem("level", data.level); |
||||||
|
sessionStorage.setItem("token", data.token); |
||||||
|
sessionStorage.setItem("refreshToken", data.refreshToken); |
||||||
|
sessionStorage.setItem("isDefaultPassword", data.isDefaultPassword); //是否需要修改默认密码
|
||||||
|
sessionStorage.setItem("singleSignOn", "true"); //是否需要修改默认密码
|
||||||
|
resolve(); |
||||||
|
}, |
||||||
|
(err) => { |
||||||
|
reject(); |
||||||
|
} |
||||||
|
); |
||||||
|
}); |
||||||
|
} |
||||||
} |
} |
||||||
|
Loading…
Reference in new issue