0

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']);
      }
    });
  }
}
rji rji
  • 697
  • 3
  • 17
  • 37

1 Answers1

0

You are using localStorage for managing the login state. When you close the page, the session remains but the timeout code stops running. You can switch to sessionStorage which will tie the login session to that tab only. However, this does mean users will have to login if they use a secured link to open another tab.

If you wish to continue using localStorage for managing the login, the other option is to trigger a logout when the tab or browser is closed. See How can we detect when user closes browser? for more info.