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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@thermopylae/lib.user-session

v1.0.1

Published

Stateful implementation of the user session.

Downloads

1

Readme

Stateful implementation of the user session.

Install

npm install @thermopylae/lib.user-session

Usage

This is a simple example of how this package can be used.

First, you need to implement storage for user sessions. In this example we will build an in-memory storage, although it's recommended to implement a persistent storage (e.g. by using Redis).

// storage.ts

import type { Seconds } from '@thermopylae/core.declarations';
import {
    PolicyBasedCache,
    AbsoluteExpirationPolicyArgumentsBundle,
    BucketGarbageCollector,
    EsMapCacheBackend,
    ProactiveExpirationPolicy,
    CacheEvent
} from '@thermopylae/lib.cache';
import type { SessionId, DeviceBase } from '@thermopylae/lib.user-session.commons';
import type { UserSessionMetaData, UserSessionsStorage } from '@thermopylae/lib.user-session';

class InMemoryUserSessionStorage implements UserSessionsStorage<DeviceBase, string> {
    private readonly cache: PolicyBasedCache<string, UserSessionMetaData<DeviceBase, string>, AbsoluteExpirationPolicyArgumentsBundle>;

    private readonly userSessions: Map<string, Set<string>>;

    public constructor() {
        const backend = new EsMapCacheBackend<string, UserSessionMetaData<DeviceBase, string>>();
        const policies = [new ProactiveExpirationPolicy<string, UserSessionMetaData<DeviceBase, string>>(new BucketGarbageCollector())];
        this.cache = new PolicyBasedCache(backend, policies);

        this.userSessions = new Map<string, Set<string>>();

        this.cache.on(CacheEvent.DELETE, (sessionIdKey) => {
            const [subject, sessionId] = InMemoryUserSessionStorage.decodeSessionIdKey(sessionIdKey);

            const sessions = this.userSessions.get(subject)!;

            sessions.delete(sessionId);
            if (sessions.size === 0) {
                this.userSessions.delete(subject);
            }
        });
    }

    public async insert(subject: string, sessionId: SessionId, metaData: UserSessionMetaData<DeviceBase, string>, ttl: Seconds): Promise<void> {
        let sessions = this.userSessions.get(subject);
        if (sessions == null) {
            sessions = new Set<string>();
            this.userSessions.set(subject, sessions);
        }

        sessions.add(sessionId);
        this.cache.set(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId), metaData, { expiresAfter: ttl });
    }

    public async read(subject: string, sessionId: SessionId): Promise<UserSessionMetaData<DeviceBase, string> | undefined> {
        return this.cache.get(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId));
    }

    public async readAll(subject: string): Promise<ReadonlyMap<SessionId, Readonly<UserSessionMetaData<DeviceBase, string>>>> {
        const sessions = this.userSessions.get(subject);
        if (sessions == null) {
            return new Map();
        }

        const sessionsMetaData = new Map<SessionId, UserSessionMetaData<DeviceBase, string>>();
        for (const sessionId of sessions) {
            sessionsMetaData.set(sessionId, this.cache.get(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId))!);
        }
        return sessionsMetaData;
    }

    public async updateAccessedAt(subject: string, sessionId: SessionId, metaData: UserSessionMetaData<DeviceBase, string>): Promise<void> {
        this.cache.set(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId), metaData);
    }

    public async delete(subject: string, sessionId: SessionId): Promise<void> {
        this.cache.del(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId));
    }

    public async deleteAll(subject: string): Promise<number> {
        const sessions = Array.from(this.userSessions.get(subject) || new Set<string>());

        for (const sessionId of sessions) {
            this.cache.del(InMemoryUserSessionStorage.sessionIdKey(subject, sessionId));
        }

        return sessions.length;
    }

    private static sessionIdKey(subject: string, sessionId: SessionId): string {
        return `${subject}:${sessionId}`;
    }

    private static decodeSessionIdKey(sessionIdKey: string): [string, SessionId] {
        return sessionIdKey.split(':') as [string, SessionId];
    }
}

export { InMemoryUserSessionStorage };

After that, we can create our UserSessionManager instance and manage user sessions.

// session.ts
import { UserSessionManager } from '@thermopylae/lib.user-session';
import { InMemoryUserSessionStorage } from './storage';

const manager = new UserSessionManager({
    idLength: 24,
    sessionTtl: 86_400, // 24h
    timeouts: {
        idle: 1_800, // 30 min
        renewal: 43_200, // 12h
        oldSessionAvailabilityAfterRenewal: 5 // 5 seconds
    },
    storage: new InMemoryUserSessionStorage(),
    renewSessionHooks: {
        onRenewMadeAlreadyFromCurrentProcess(sessionId) {
            console.warn(
                `Can't renew session '${UserSessionManager.hash(sessionId)}', because it was renewed already. Renew has been made from this NodeJS process.`
            );
        },
        onRenewMadeAlreadyFromAnotherProcess(sessionId) {
            console.warn(
                `Can't renew session '${UserSessionManager.hash(sessionId)}', because it was renewed already. Renew has been made from another NodeJS process.`
            );
        },
        onOldSessionDeleteFailure(sessionId, error) {
            console.error(`Failed to delete renewed session '${UserSessionManager.hash(sessionId)}'.`, error);
        }
    }
});

(async function main() {
    /* Create session */
    let sessionId = await manager.create('uid1', { ip: '127.0.0.1' });

    /* Read it */
    const [sessionMetaData, renewedSessionId] = await manager.read('uid1', sessionId, { ip: '127.0.0.1' });
    console.log(`Session meta data associated with session id '${sessionId}': ${JSON.stringify(sessionMetaData)}`);
    if (renewedSessionId != null) {
        console.warn(`User session was renewed and the new session id '${renewedSessionId}' needs to be sent to client.`);
        sessionId = renewedSessionId; // the old one is no longer valid
    }

    /* Read all active sessions */
    const activeSessions = await manager.readAll('uid1');
    console.log(`User with id 'uid1' has ${activeSessions.size} active sessions.`);

    /* Delete session */
    await manager.delete('uid1', sessionId);

    /* Delete all sessions */
    const deletedSessionsNo = await manager.deleteAll('uid1');
    console.info(`Deleted ${deletedSessionsNo} active sessions of user with id 'uid1'.`);
})();

API Reference

API documentation is available here.

It can also be generated by issuing the following commands:

git clone [email protected]:marinrusu1997/thermopylae.git
cd thermopylae
yarn install
yarn workspace @thermopylae/lib.user-session run doc

Author

👤 Rusu Marin

📝 License

Copyright © 2021 Rusu Marin. This project is MIT licensed.