npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sauravart/fgs-session-management

v1.0.0

Published

Angular session management library with timeout handling, activity tracking, multi-session conflict detection, and UI components

Downloads

97

Readme

FGS Session Management

A comprehensive Angular library for session management with timeout handling, activity tracking, multi-session conflict detection, and beautiful Tailwind CSS UI components.

Features

  • Session Timer: Configurable session timeout with warning countdown
  • Activity Tracking: Monitors user activity (mouse, keyboard, scroll, touch)
  • Token Management: Cookie + sessionStorage dual token storage
  • Auth Interceptor: Automatic header injection and 401 handling
  • Auth Guards: Route protection with role/permission support
  • Multi-Session Detection: Detect and manage concurrent sessions
  • UI Components: Beautiful Tailwind CSS timeout dialog and conflict modal
  • Device Fingerprinting: Unique device identification
  • IP Geolocation: Location tracking for session security

Installation

npm install @sauravart/fgs-session-management

Requirements

  • Angular 17+
  • RxJS 7+
  • Tailwind CSS (for UI components)

Quick Start

1. Configure the Provider

// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideFgsSession, fgsSessionInterceptor } from '@sauravart/fgs-session-management';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideHttpClient(withInterceptors([fgsSessionInterceptor])),
    provideFgsSession({
      apiBaseUrl: 'https://your-api.com/api',
      endpoints: {
        createSession: '/Session/create',
        validateSession: '/Session/validate',
        refreshSession: '/Auth/refreshsession',
        revokeSession: '/Session/revoke',
        listSessions: '/Session/list',
        logout: '/Auth/removesession'
      },
      sessionTimeoutMs: 600000, // 10 minutes
      warningWindowSeconds: 60,
      features: {
        enableMultiSessionDetection: true,
        enableDeviceFingerprint: true,
        enableIPGeolocation: true,
        enableActivityTracking: true
      }
    })
  ]
};

2. Add UI Components to App Component

// app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {
  FgsSessionTimeoutDialogComponent,
  FgsSessionConflictModalComponent
} from '@sauravart/fgs-session-management';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    RouterOutlet,
    FgsSessionTimeoutDialogComponent,
    FgsSessionConflictModalComponent
  ],
  template: `
    <router-outlet />
    <fgs-session-timeout-dialog />
    <fgs-session-conflict-modal />
  `
})
export class AppComponent {}

3. Initialize Session After Login

// login.component.ts
import { Component, inject } from '@angular/core';
import { FgsSessionService } from '@sauravart/fgs-session-management';

@Component({...})
export class LoginComponent {
  private sessionService = inject(FgsSessionService);

  async onLogin(credentials: { email: string; password: string }) {
    // Your login API call
    const loginResponse = await this.authService.login(credentials);

    // Initialize session management
    await this.sessionService.initializeSession(
      loginResponse.userData,
      loginResponse.authToken,
      loginResponse.userId
    );

    // Navigate to dashboard
    this.router.navigate(['/dashboard']);
  }
}

4. Protect Routes with Guards

// app.routes.ts
import { Routes } from '@angular/router';
import { fgsSessionGuard, fgsGuestGuard, fgsRoleGuard } from '@sauravart/fgs-session-management';

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [fgsGuestGuard] // Only for non-authenticated users
  },
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [fgsSessionGuard] // Requires authentication
  },
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [fgsSessionGuard, fgsRoleGuard(['admin', 'superadmin'])]
  }
];

Configuration Options

interface FgsSessionConfig {
  // Required
  apiBaseUrl: string;
  endpoints: {
    createSession: string;
    validateSession: string;
    refreshSession: string;
    revokeSession: string;
    listSessions: string;
    logout: string;
  };

  // Timeout Settings
  sessionTimeoutMs?: number;        // default: 600000 (10 min)
  warningWindowSeconds?: number;    // default: 60
  activityThrottleMs?: number;      // default: 1000
  refreshThrottleMs?: number;       // default: 30000
  validationThrottleMs?: number;    // default: 5000

  // Storage Keys
  storageKeys?: {
    authToken?: string;             // default: 'Authtoken'
    sessionId?: string;             // default: 'sessionId'
    sessionAuthToken?: string;      // default: 'sessionAuthToken'
    userData?: string;              // default: 'localUserData'
    lastApiCallTime?: string;       // default: 'lastApiCallTime'
    lastActivity?: string;          // default: 'userLastActivity'
    deviceId?: string;              // default: 'deviceId'
  };

  // Cookie Config
  cookieConfig?: {
    name?: string;                  // default: 'Authtoken'
    secure?: boolean;               // default: true
    sameSite?: 'strict' | 'lax';    // default: 'strict'
    path?: string;                  // default: '/'
  };

  // Feature Flags
  features?: {
    enableMultiSessionDetection?: boolean;  // default: true
    enableDeviceFingerprint?: boolean;      // default: true
    enableIPGeolocation?: boolean;          // default: true
    enableActivityTracking?: boolean;       // default: true
  };

  // UI Customization
  ui?: {
    showTimeoutDialog?: boolean;
    showConflictModal?: boolean;
    dialogTitle?: string;
    dialogMessage?: string;
    dialogExtendButtonText?: string;
    dialogLogoutButtonText?: string;
    conflictModalTitle?: string;
    conflictModalMessage?: string;
    forceLogoutDelaySeconds?: number;
  };

  // Routes
  routes?: {
    loginRoute?: string;            // default: '/'
    afterLoginRoute?: string;       // default: '/home'
  };

  // Callbacks
  callbacks?: {
    onSessionCreated?: (session) => void;
    onSessionExpired?: () => void;
    onSessionExtended?: () => void;
    onForceLogout?: () => void;
    onConflictDetected?: (sessions) => void;
    onLogout?: () => void;
    onUnauthorized?: () => void;
  };

  // IP Geolocation
  geolocation?: {
    apiUrl?: string;                // default: 'http://ip-api.com/json'
    timeout?: number;               // default: 5000
  };

  // Debug
  debug?: boolean;                  // default: false
}

Services

FgsSessionService

Main service for session management.

import { FgsSessionService } from '@sauravart/fgs-session-management';

@Component({...})
export class MyComponent {
  private sessionService = inject(FgsSessionService);

  // Initialize session after login
  async initSession(userData: any, token: string) {
    await this.sessionService.initializeSession(userData, token);
  }

  // Extend session
  extendSession() {
    this.sessionService.extendSession().subscribe();
  }

  // Logout
  logout() {
    this.sessionService.logout().subscribe();
  }

  // Check authentication
  get isAuthenticated() {
    return this.sessionService.isAuthenticated();
  }
}

FgsSessionTimerService

Manage session timeout.

import { FgsSessionTimerService } from '@sauravart/fgs-session-management';

@Component({...})
export class MyComponent {
  private timer = inject(FgsSessionTimerService);

  ngOnInit() {
    // Subscribe to timer
    this.timer.timerTrigger$.subscribe(seconds => {
      if (seconds > 0) {
        console.log(`Session expires in ${seconds} seconds`);
      }
    });

    // Subscribe to expiry
    this.timer.sessionExpired$.subscribe(() => {
      console.log('Session expired!');
    });
  }

  // Get remaining time
  getRemainingTime() {
    return this.timer.getRemainingTimeSeconds();
  }
}

FgsStorageService

Manage session storage.

import { FgsStorageService } from '@sauravart/fgs-session-management';

@Component({...})
export class MyComponent {
  private storage = inject(FgsStorageService);

  // Get user data
  getUserData() {
    return this.storage.getUserData();
  }

  // Check authentication
  isAuthenticated() {
    return this.storage.isAuthenticated();
  }

  // Clear all session data
  clearSession() {
    this.storage.clearAll();
  }
}

Guards

fgsSessionGuard

Protects routes requiring authentication.

{
  path: 'protected',
  component: ProtectedComponent,
  canActivate: [fgsSessionGuard]
}

fgsGuestGuard

Only allows unauthenticated users (for login page).

{
  path: 'login',
  component: LoginComponent,
  canActivate: [fgsGuestGuard]
}

fgsRoleGuard

Role-based access control.

{
  path: 'admin',
  component: AdminComponent,
  canActivate: [fgsSessionGuard, fgsRoleGuard(['admin'])]
}

fgsPermissionGuard

Permission-based access control.

{
  path: 'reports',
  component: ReportsComponent,
  canActivate: [fgsSessionGuard, fgsPermissionGuard(['view_reports'])]
}

UI Components

Session Timeout Dialog

Displays countdown when session is about to expire.

<fgs-session-timeout-dialog />

Features:

  • Circular countdown timer
  • Extend session button
  • Logout button
  • Dark mode support

Session Conflict Modal

Shows when multiple sessions are detected.

<fgs-session-conflict-modal />

Features:

  • List of active sessions with device info
  • Force logout other sessions
  • Cancel and logout option
  • Countdown before force logout is enabled

Tailwind CSS Setup

The UI components use Tailwind CSS classes. Make sure Tailwind is configured in your project.

// tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{html,ts}",
    "./node_modules/@sauravart/fgs-session-management/**/*.{html,ts,mjs}"
  ],
  // ... rest of config
}

API Endpoints Expected

The library expects the following API endpoints:

POST /Session/create

Create a new session.

Request:

{
  "userId": "string",
  "deviceId": "string",
  "deviceName": "string",
  "browser": "string",
  "os": "string",
  "ipAddress": "string",
  "location": "string",
  "userAgent": "string"
}

Response:

{
  "sessionId": "string",
  "sessionAuthToken": "string",
  "expiresAt": "string"
}

GET /Session/validate

Validate current session.

Response:

{
  "valid": true,
  "sessionId": "string"
}

POST /Auth/refreshsession

Refresh session token.

Response:

{
  "success": true,
  "sessionAuthToken": "string"
}

GET /Session/list/{userId}

List active sessions for user.

Response:

[
  {
    "sessionId": "string",
    "deviceName": "string",
    "browser": "string",
    "os": "string",
    "ipAddress": "string",
    "location": "string",
    "lastActivity": "string",
    "isCurrent": false
  }
]

POST /Session/revoke/{sessionId}

Revoke a specific session.

POST /Auth/removesession

Logout and end session.

License

MIT