Monitoring User Interactions for Maintaining Session Foresight Plan utilizing RxJS

My goal is to maintain user session activity by implementing a system that locks an interactive session after 15 minutes of user inactivity (defined as no keyboard or mouse activity).

The information system will automatically lock the session if there is no user activity for 15 minutes.

I have come up with a solution using RxJS, but I'm open to suggestions for better or standard strategies.

In the example below, the server will be pinged every 60 seconds if there is any user activity.

const userActivityEvents = [
      fromEvent(document, 'click'),
      fromEvent(document, 'wheel'),
      fromEvent(document, 'scroll'),
      fromEvent(document, 'keypress'),
      fromEvent(document, 'mousemove'),
      fromEvent(document, 'touchmove'),
    ];

    merge(...userActivityEvents).pipe(
      throttleTime(60 * 1000),
      switchMap(() => this.apiService.get('/api/auth/ping', new HttpParams(), new HttpHeaders({ignoreLoadingBar: ''})),
      ),
    ).subscribe({error: () => undefined});

Answer №1

Seeing as there hasn't been any progress on this matter, I believe it's time for me to provide my final response.


      this.ngZone.runOutsideAngular(() => {
        merge(
          fromEvent(document, 'click'),
          fromEvent(document, 'wheel'),
          fromEvent(document, 'scroll'),
          fromEvent(document, 'keypress'),
          fromEvent(document, 'mousemove'),
          fromEvent(document, 'touchmove'),
        ).pipe(
          throttleTime(USER_ACTIVITY_POLL_TIME),
          skip(1),
          filter(() => !this.sessionModal),
          filter(() => this.authService.authenticated),
          switchMap(() => this.authService.ping(new HttpHeaders({ignoreLoadingBar: ''}))),
        ).subscribe({error: () => undefined});
      });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

Event typeORM on afterUpdate in NestJS

After every update of my data in the log table, I want to insert an entry into another table. To achieve this, I have created an EntitySubscriberInterface. The event is triggering correctly, but the entity array does not include the updated id. async afte ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

Using Angular 5 for sending HTTP POST requests with x-www-form-urlencoded content-type

Currently, I have been immersing myself in Angular and am nearing completion of my initial end-to-end application. This specific app is designed to interact with Spotify's public API in order to search for music and play track previews. The primary i ...

Tips for obtaining results from a File Reader

I am currently facing an issue with an onchange event in my HTML. The event is intended to retrieve an image from the user, convert it to a data URL, and then send it over socket.io to store in the database. However, I am struggling to figure out how to ac ...

Leverage generic types and allow acceptance of objects with arbitrary keys

Is it possible to allow the Use function argument type to accept any unknown key, as well as correctly type the keys from SomeGeneric? function Example (opt: { valid?: boolean }) { } type SomeGeneric = Parameters<typeof Example>[0] function Use(op ...

The variable 'form' has not been assigned an initial value in the constructor of the property

Below is the snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-license', te ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

Steps to resolve the issue of receiving a warning while utilizing @babel/plugin-transform-typescript for compiling TypeScript code

Every time I compile TypeScript using @babel/plugin-transform-typescript, I encounter a warning. The issue seems to be caused by another plugin injecting "_class" without properly registering it in the scope tracker. If you are the creator of that plugin, ...

Unlocking The Mystery of Disappearing Inputs on Ionic 5

How can I prevent Ionic 6 (Angular) from hiding inputs when the keyboard shows? Whenever I focus on an input, the keyboard covers it. Is there a way to automatically scroll so the keyboard is positioned below the selected input? View Image of Input/Keyboa ...

Attempting to access jQuery from an external JavaScript file within the Ionic 5 framework

Currently, I am working on an Ionic app with Angular. I want to call my JavaScript function when the document is ready in the JS file, but I keep encountering an error. Here is my watch.page.html: <ion-content> <div class="videoContainer&qu ...

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

Learn how to implement AuthContext and createDataContext in React Native Expo development using TypeScript

AuthContext.tsx import createDataContext from './createDataContext'; import serverApi from '../api/server'; const authReducer = ({state, action}: any) => { switch(action.type){ default: return state; } } ...

Angular 9 - Button unable to be clicked under certain conditions

I have a webpage that contains a lot of information, and I would like to make it easier for the user to show/hide specific parts by clicking on buttons. Check out this stackblitz to see what I've done. Here's a brief summary of the code: <but ...

Bidirectional binding of ngModel across components with validation

I am attempting to link a value from the parent component to the child component for reusability. parent-component.ts profile:any = {name:"", mobile:""} Parent-component.html <app-profile-name label="Name" [(name)]="profile.name"></app-profil ...

Can dynamic string types be declared in Typescript?

Let's consider the following scenario: export enum EEnv { devint, qa1 }; export type TEnv = keyof typeof EEnv; export const env:Record<TEnv, {something:number}> = { devint: { something: 1, }, qa1: { something: 1, }, } Now, I ai ...

Angular6 returns the result after subscribing to an HTTP POST request

Currently, I am in the process of learning angular and attempting to create a component that allows users to register through my web API. Within my component, the code on form submission looks like this: onSubmit(contactFormRef: NgForm) { const resu ...

Utilizing Typescript to Inject Generics and Retrieve the Name of an ES6 Module

I am currently working on developing a versatile repository using: Typescript ES6 Angular 1.x However, I am facing challenges in determining the correct way to inject the Entity and retrieve its module name. The main reason for needing the name: I adh ...