我已使用以下代码进行超时。当我登录并保持非活动状态 1 小时时,超时工作成功并且用户正在注销。
但是当我登录并关闭浏览器并在 1 小时后返回并在浏览器中打开应用程序时,会话仍然存在并且用户仍然登录。
为什么我只能注销如果应用程序已打开且处于非活动状态,如果我关闭浏览器并在 1 小时后返回,为什么它不会被注销
import { Router } from '@angular/router';
import { AuthenticationService } from '../_services/authentication.service';
import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs';
const MINUTES_UNITL_AUTO_LOGOUT = 1 // in Minutes
const CHECK_INTERVALL = 1000 // in ms
const STORE_KEY = 'lastAction';
@Injectable({
providedIn: 'root'
})
export class AutoLogoutService {
isSuperadmin$ : Observable<boolean>;
isLoggedIn$ : Observable<boolean>;
islogin = false;
constructor(
private auth: AuthenticationService,
private router: Router,
private ngZone: NgZone
) {
this.isLoggedIn$ = this.auth.isUserLoggedIn;
this.isSuperadmin$ = this.auth.isSuperadmin;
this.lastAction(Date.now());
this.check();
this.initListener();
this.initInterval();
}
getlastAction() {
return localStorage.getItem('lastaction');
}
lastAction(value) {
localStorage.setItem('lastaction', JSON.stringify(value))
}
initListener() {
this.ngZone.runOutsideAngular(() => {
document.body.addEventListener('click', () => this.reset());
});
}
initInterval() {
this.ngZone.runOutsideAngular(() => {
setInterval(() => {
this.check();
}, CHECK_INTERVALL);
})
}
reset() {
this.lastAction(Date.now());
}
check() {
const now = Date.now();
const timeleft = parseInt(this.getlastAction()) + MINUTES_UNITL_AUTO_LOGOUT * 60 * 1000;
const diff = timeleft - now;
const isTimeout = diff < 0;
this.isLoggedIn$.subscribe(event => this.islogin = event);
this.ngZone.run(() => {
if (isTimeout && this.islogin) {
this.auth.logout();
this.router.navigate(['/admin/login']);
}
});
}
}