Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give session idle timeout in angular 6?

We are maintaining a session based on user role. We want to implement timeout functionality when the session is idle for 5 min. We are using @ng-idle/core npm module to do that.

My Service file:

 import { ActivatedRouteSnapshot } from '@angular/router';
 import { RouterStateSnapshot } from '@angular/router';
 import {Idle, DEFAULT_INTERRUPTSOURCES, EventTargetInterruptSource} from 
 '@ng-idle/core';
 @Injectable()
export class LoginActService implements CanActivate {
constructor(private authService: APILogService, private router: 
 Router,private idle: Idle) {
  idle.setIdle(10);
  idle.setTimeout(10);
 }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
 ): Observable<boolean>|Promise<boolean>|boolean {
let role = localStorage.getItem('currentUser');

if (localStorage.getItem('currentUser')) {
  if(next.data[0] == role){
   },600000) 
    return true;
  } 
}
else{
  this.router.navigate(['/'], { queryParams: { returnUrl: state.url }});
  return false;
  }
 }
}

For sample, I have used setIdle timeout for 5 seconds, But it is not happening. Can somebody guide me how to do this?

like image 499
viki Avatar asked Feb 28 '19 12:02

viki


People also ask

How to handle user idleness and session timeout in angular?

You can use bn-ng-idle npm for user idle / session timeout detection in angular apps. This blog post explanation will help you Learn how to Handle user idleness and session timeout in Angular

How long should idle time and timeout time be set to?

I set both idle time and timeout time to 5 seconds for the demonstration purpose. Usually, these times are longer in the actual environments, typically it is around 15 mins. I want to show a modal window whenever the user is idle and give some options for the user to logout or stay as shown in the figure.

Why do we use setTimeout() function in angular?

We can use the setTimeout () function for various reasons. It is best to allow Angular to run change detection once, between the actions that we would otherwise perform synchronously. setTimeout () is a native JavaScript function that sets a timer to execute a callback function, calling the function once the timer is done.

How to detect the idle user in AngularJS?

We can actually detect the idle user with the help of DOM events: keyboard events and mouse events. For Angular applications, we can use the ng-idle library. We can conditionally watch and unwatch the user with the help of idle.watch and idle.start methods from ng-idle lib.


4 Answers

You can use bn-ng-idle npm for user idle / session timeout detection in angular apps. This blog post explanation will help you Learn how to Handle user idleness and session timeout in Angular

npm install bn-ng-idle

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { BnNgIdleService } from 'bn-ng-idle'; // import bn-ng-idle service
 
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [BnNgIdleService], // add it to the providers of your module
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { BnNgIdleService } from 'bn-ng-idle'; // import it to your component
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  constructor(private bnIdle: BnNgIdleService) { // initiate it in your component constructor
    this.bnIdle.startWatching(300).subscribe((res) => {
      if(res) {
          console.log("session expired");
      }
    })
  }
}

In the above example, I have invoked the startWatching(timeOutSeconds) method with 300 seconds (5 minutes) and subscribed to the observable, once the user is idle for five minute then the subscribe method will get invoked with the res parameter's value (which is a boolean) as true.

By checking whether the res is true or not, you can show your session timeout dialog or message. For brevity, I just logged the message to the console.

like image 143
Bear Nithi Avatar answered Oct 18 '22 02:10

Bear Nithi


Option: 1: angular-user-idle.

Logic

  • Library are waiting for a user's inactive for a 1 minutes (60 seconds).

  • If inactive are detected then onTimerStart() is fired and
    returning a countdown for a 2 minutes (120 seconds).

  • If user did notstop the timer by stopTimer() then time is up after 2 minutes (120 seconds) and onTimeout() is fire.

In AppModule:

@NgModule({
      imports: [
        BrowserModule,

        // Optionally you can set time for `idle`, `timeout` and `ping` in seconds.
        // Default values: `idle` is 600 (10 minutes), `timeout` is 300 (5 minutes) 
        // and `ping` is 120 (2 minutes).
        UserIdleModule.forRoot({idle: 600, timeout: 300, ping: 120})
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })

In any of your core componets:

    ngOnInit() {
        //Start watching for user inactivity.
        this.userIdle.startWatching();

        // Start watching when user idle is starting.
        this.userIdle.onTimerStart().subscribe(count => console.log(count));

        // Start watch when time is up.
        this.userIdle.onTimeout().subscribe(() => console.log('Time is up!'));
      }

Bonus: You can use "ping" to make request to refresh token in a given interval of time (e.g. every 10 mins).

Option: 2: Using ngrx

Please refer to the article in the link: https://itnext.io/inactivity-auto-logout-w-angular-and-ngrx-3bcb2fd7983f

like image 42
Prateek Kumar Dalbehera Avatar answered Oct 18 '22 03:10

Prateek Kumar Dalbehera


you can use the code below on the main or parent component. Let's say this is in the admin parent component and am assuming you have an authentication service so that you can know whether the user is logged

declare variables

   userActivity;
   userInactive: Subject<any> = new Subject();

in the constructor or on ngOnInit add

this.setTimeout();
 this.userInactive.subscribe(() => {
   this.logout();
 });  
 logout() {
 this.authService.logout();
 this.authService.redirectLogoutUser();
}

finally add the following methods

    setTimeout() {
    this.userActivity = setTimeout(() => {
      if (this.authService.isLoggedIn) {
        this.userInactive.next(undefined);
        console.log('logged out');
      }
    }, 420000);
  }

  @HostListener('window:mousemove') refreshUserState() {
    clearTimeout(this.userActivity);
    this.setTimeout();
  }
like image 8
Eyayu Tefera Avatar answered Oct 18 '22 02:10

Eyayu Tefera


I have added this.bnIdle.stopTimer() in Angular8 after the timeout, because when I visit the same component there is a glitch in timing.

--> I subscribed and unsubscribed in ngOnDestroy but then to the timer was not stopping.

--> found the stopTimer and implemented it and it is working perfectly fine for me. Hope it will help others.

this.bnIdle.startWatching(300).subscribe((res) => {
          if(res) {
              console.log("session expired");
        this.bnIdle.stopTimer();
          }
        });
like image 1
syed Avatar answered Oct 18 '22 04:10

syed