angular-user-idle

repository·main·Indexed 41 days ago

https://github.com/rednez/angular-user-idle

A service for Angular 15+ applications designed to detect user inactivity and manage idle/timeout lifecycles. Version 4.0.0 introduces provideUserIdleConfig for configuration. It provides the UserIdleService to monitor activity via startWatching(), handle countdowns with onTimerStart(), and trigger actions on timeout with onTimeout(). It includes a ping mechanism for periodic actions and supports custom activity events.

Tokens
3.7K
Snippets
12
Records
13
Agent score
52%

What's inside angular-user-idle

  1. How the ping mechanism works

    main

    The ping interval allows you to perform periodic actions (like refreshing an authentication token) during the lifecycle between the user becoming idle and the timeout occurring.

    Lifecycle Example: If ping is 2m, idle is 10m, and timeout is 5m:

    1. User is active.
    2. At 10m (idle detected), the countdown timer starts.
    3. Every 2m (ping), an event is emitted.
    4. At 15m (total time), the timeout fires.

    Timeline: |–– 2m (ping)––4m (ping) ––6m (ping)...-– 10m (user idle detected, start timer for 5 min) –- 12m (ping) –– 14m (ping) –– 15m (time is out)|

    // Example: Refresh token every 2 minutes using ping
    this.userIdle.ping$.subscribe(() => console.log("PING"));
  2. Configure angular-user-idle in AppModule

    main

    To use the library in Angular 15+, provide the configuration using provideUserIdleConfig in your AppModule providers array. You can optionally set the following durations in seconds:

    • idle: Time (in seconds) before the user is considered idle. Default is 600 (10 minutes).
    • timeout: Time (in seconds) after the idle timer starts before a timeout occurs. Default is 300 (5 minutes).
    • ping: Interval (in seconds) to perform periodic actions during the lifecycle. Default is 120 (2 minutes).
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { provideUserIdleConfig } from 'angular-user-idle';
    import { AppComponent } from './app.component';
    
    @NgModule({
      imports: [BrowserModule],
      declarations: [AppComponent],
      providers: [
        // Optionally you can set time for `idle`, `timeout` and `ping` in seconds.
        provideUserIdleConfig({ idle: 600, timeout: 300, ping: 120 })
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
  3. Use UserIdleService to monitor inactivity

    main

    Inject UserIdleService into your components or services to manage user activity monitoring. You must call startWatching() to begin the process.

    Common workflow:

    1. Call startWatching() to begin monitoring.
    2. Subscribe to onTimerStart() to receive the countdown value when the idle period begins.
    3. Subscribe to onTimeout() to handle the event when the timeout period expires.
    4. Use stopWatching() to halt the service or stopTimer() to stop the current countdown.
    import { Component, OnInit } from '@angular/core';
    import { UserIdleService } from 'angular-user-idle';
    
    @Component({
      templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
      constructor(private userIdle: UserIdleService) {}
    
      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!'));
      }
    
      stop() {
        this.userIdle.stopTimer();
      }
    
      stopWatching() {
        this.userIdle.stopWatching();
      }
    
      startWatching() {
        this.userIdle.startWatching();
      }
    
      restart() {
        this.userIdle.resetTimer();
      }
    }
  4. UserIdleService API Reference

    main

    The UserIdleService provides the following methods to control and observe user activity:

    • startWatching(): void: Starts the user idle service and configures it.
    • onTimerStart(): Observable<number|null>: Fired when the countdown timer starts. Returns an observable stream of the remaining count, or null if stopWatching() was called.
    • onTimeout(): Observable<boolean>: Fired when the timeout period expires without the timer being stopped.
    • stopTimer(): Stops the current countdown timer.
    • resetTimer(): Resets the timer after onTimeout() has been fired.
    • stopWatching(): Stops the entire user idle service.
    • setConfigValues({idle, timeout, ping}): Updates configuration values after the module has been initialized.
    • setCustomActivityEvents(customEvents: Observable<any>): void: Sets custom activity events to be used by the service after initialization.
  5. Configure UserIdleConfig options

    main

    The UserIdleConfig class defines the settings for the idle detection behavior. You can provide these settings using the provideUserIdleConfig function during application setup.

    Available configuration properties:

    • idle (number, optional): The amount of time in seconds before the user is considered idle.
    • timeout (number, optional): The amount of time in seconds before a timeout action is triggered.
    • ping (number, optional): The interval in seconds at which a ping is sent to check activity.
    • idleSensitivity (number, optional): The time in seconds that activity must remain below the idle detection threshold before the idle buffer timer counts the user's activity actions.
    export class UserIdleConfig {
      /**
       * Idle value in seconds.
       */
      idle?: number;
      /**
       * Timeout value in seconds.
       */
      timeout?: number;
      /**
       * Ping value in seconds.
       */
      ping?: number;
      /**
       * IdleSensitivity time that activity must remain below the idle detection threshold before
       * idle buffer timer count user's activity actions, in seconds.
       */
      idleSensitivity?: number;
    }
  6. Configure UserIdleService settings

    main

    You can configure the behavior of the UserIdleService using a UserIdleConfig object. Configuration can be provided during service instantiation (via dependency injection) or updated dynamically.

    Configuration Options

    • idle: The time (in seconds) after which the user is considered idle. (Default: 600s / 10m)
    • ping: The interval (in seconds) for the ping$ observable. (Default: 120s / 2m)
    • idleSensitivity: The buffer time (in seconds) used to collect user actions before detecting inactivity. (Default: 1s)
    • timeout: The total time (in seconds) before a timeout event is fired. (Default: 300s / 5m)

    Updating Configuration

    To update settings after the service has been initialized, you must call stopWatching() before applying new values via setConfigValues(config).

    To see the current effective configuration (converted to seconds), use getConfigValue().

    this.idleService.setConfigValues({
      idle: 300,           // 5 minutes
      timeout: 600,        // 10 minutes
      ping: 60,            // 1 minute
      idleSensitivity: 2  // 2 seconds
    });
  7. Configure UserIdle using provideUserIdleConfig

    main

    As of version 4.0.0, the recommended way to configure the library is using the provideUserIdleConfig function instead of the deprecated UserIdleModule.forRoot() method. This function accepts a UserIdleConfig object and should be used within your application's provider configuration (e.g., in app.config.ts for standalone applications or within the providers array of an @NgModule).

    // Example for standalone applications (app.config.ts)
    export const appConfig: ApplicationConfig = {
      providers: [
        provideUserIdleConfig({
          // ... your UserIdleConfig options
        })
      ]
    };
  8. Provide UserIdleConfig in Angular application

    main

    To use the idle detection service, you must register the configuration in your application's provider list using provideUserIdleConfig. This function returns EnvironmentProviders and should be called within your app.config.ts (for standalone applications) or your AppModule providers array.

    Example usage in a standalone application setup:

    import { provideUserIdleConfig } from 'angular-user-idle';
    
    export const appConfig: ApplicationConfig = {
      providers: [
        provideUserIdleConfig({
          idle: 300,      // 5 minutes
          timeout: 600,   // 10 minutes
          ping: 60,       // 1 minute
          idleSensitivity: 10
        })
      ]
    };
  9. Manage user idle state with UserIdleService

    main

    The UserIdleService is the primary service for detecting user inactivity and managing timeout timers. It monitors user activity (like mouse movement or key presses) and provides Observables to react to idle detection, timer starts, and timeouts.

    Core Lifecycle Methods

    • startWatching(): Initializes activity monitoring, sets up the idle timer, and starts the ping interval. You must call this to begin tracking.
    • stopWatching(): Stops all monitoring, clears the idle subscription, and stops the timer.
    • resetTimer(): Stops the current inactivity timer and resets the timeout status.
    • stopTimer(): Stops the current inactivity timer without resetting the timeout status.

    Reacting to Idle Events

    Use these methods to subscribe to state changes:

    • onIdleStatusChanged(): Returns an Observable<boolean> that emits true when the user becomes idle and false when they become active again.
    • onTimerStart(): Returns an Observable<number> that emits the elapsed seconds of the countdown timer once the idle threshold is reached.
    • onTimeout(): Returns an Observable<boolean> that emits when the configured timeout period has expired.
    import { UserIdleService } from 'angular-user-idle';
    
    // Inside your component or service
    constructor(private idleService: UserIdleService) {
      this.idleService.startWatching();
    
      this.idleService.onIdleStatusChanged().subscribe(isIdle => {
        console.log('Is user idle?', isIdle);
      });
    
      this.idleService.onTimerStart().subscribe(seconds => {
        console.log(`Timer started. Seconds elapsed: ${seconds}`);
      });
    
      this.idleService.onTimeout().subscribe(isTimeout => {
        if (isTimeout) {
          console.log('User has timed out!');
        }
      });
    }
  10. Define custom activity events

    main

    By default, the service monitors mousemove, resize, and keydown events on the window and document. If you need to include other events (like touch events for mobile support), use setCustomActivityEvents(customEvents).

    Note: You must call stopWatching() before calling this method. The customEvents parameter expects an RxJS Observable<any> representing the merged stream of activity events.

    import { merge, fromEvent } from 'rxjs';
    
    const customEvents = merge(
      fromEvent(window, 'mousemove'),
      fromEvent(document, 'touchstart'),
      fromEvent(document, 'touchend')
    );
    
    this.idleService.stopWatching();
    this.idleService.setCustomActivityEvents(customEvents);
    this.idleService.startWatching();
  11. Deprecated: Configure UserIdle using UserIdleModule.forRoot()

    main

    The UserIdleModule.forRoot(config: UserIdleConfig) method is deprecated as of version 4.0.0. If you are working in a legacy Angular application using NgModule, you can still use this method to provide the configuration, but it is recommended to migrate to provideUserIdleConfig.

    @NgModule({
      imports: [
        UserIdleModule.forRoot({
          // ... your UserIdleConfig options
        })
      ],
    })
    export class AppModule {}