I have used the below code for timeout. When I login and stay inactive for 1 hour then the timeout is working successfully and the user is getting logout.
But when I login and close the browser and come back after 1 hour and open the application in browser then the session is still remained and user is still logged in.
Why am I able to logout only If the application is opened and inactive, why not it is getting logged out if I close the browser and come back after 1 hour
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']);
}
});
}
}