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 can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in: HTML: <div *ngFor="let report of reports"> <div *ngFor="let i of income"> <di ...

Automatic generation of generic types in higher-order functions in TypeScript

function createGenerator<P extends object>(initialize: (params: P) => void) { return function (params: P): P { initialize(params) return params } } const gen = createGenerator(function exampleFunction<T>(param: T) { console.lo ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

The separator falls short of spanning the entire width of the page

For some reason, I can't seem to make the divider extend to the full length of the page. <TableRow> <TableCell className={classes.tableCell} colSpan={6}> <Box display="grid" gridTemplateColumn ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

Creating interactive buttons within a card in Ionic 2

I created a card in Ionic 2 with the following structure. Upon clicking the card, it navigates to another page. <ion-content padding class="item item-text-wrap"> <ion-list> <ion-item *ngFor='let topic of topicList' text-wr ...

What is the best way to add a repository in Nest.js using dependency injection?

I am encountering an issue while working with NestJS and TypeORM. I am trying to call the get user API, but I keep receiving the following error message: TypeError: this.userRepository.findByIsMember is not a function. It seems like this error is occurring ...

Accessing an external API through a tRPC endpoint (tRPC Promise is resolved before processing is complete)

I want to utilize OpenAI's API within my Next.js + tRPC application. It appears that my front-end is proceeding without waiting for the back-end to finish the API request, resulting in an error due to the response still being undefined. Below is my e ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

AADSTS9002326: Token redemption across origins is only allowed for the client type of 'Single-Page Application'. Origin of request: 'capacitor://localhost'

My Ionic application is having trouble authenticating in Azure. I followed the guidance from a stackoverflow thread: Ionic and MSAL Authentication Everything went smoothly except for iOS, where I encountered the following error: AADSTS9002326: Cross ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

The appearance of the Angular app undergoes a change following deployment using ng build

I have been working with Angular for several years now, but only recently delved into using Angular Material components in my latest project. I was pleased with how my layout turned out and ready to push it to production. However, after deployment, the com ...

Revising input value post model binding

In my scenario, I have a text input that is bound to a model property of type Date: <input type="text" [(ngModel)]="model.DateStart" ngControl="dateStart" id="dateStart" #dateStart /> The value of model.DateStart (which is of type DateTime) looks l ...

Exploring the Concept of Extending Generic Constraints in TypeScript

I want to create a versatile function that can handle sub-types of a base class and return a promise that resolves to an instance of the specified class. The code snippet below demonstrates my objective: class foo {} class bar extends foo {} const someBar ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

The guidelines for implementing pipes in Angular 2

I am struggling with writing a pipe that should filter for both AUID and firstname. Unfortunately, it seems to only be working for the firstname. Can anyone help me figure out why? Below is the code snippet in question: return value.filter((searc ...

Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this: { "key" : "false", "key2" : "1.00", "key3" : "value" } I am seeking to convert this in Typescript to achieve th ...

TS - The 'new' keyword can only be used with a void function

I'm encountering a strange TypeScript error: "Only a void function can be called with the 'new' keyword." What in the world? The constructor function looks like this: function Suman(obj: ISumanInputs): void { const projectRoot = _su ...

Obtain merged types by accessing a particular property within a deeply nested object

My query is reminiscent of a post on Stack Overflow titled Get all value types of a double-nested object in TypeScript However, my specific requirement involves extracting union types from the values of a designated property. const tabsEnum = { IDCardRe ...

Bespoke Socket.io NodeJS chamber

I am currently developing an application involving sockets where the requirement is to broadcast information only to individuals within a specific room. Below is a snippet of the code from my server.ts file: // Dependencies import express from 'expre ...