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

browser-user-session

v1.0.4

Published

A lightweight package that provides helpers to manage user session.

Downloads

1,664

Readme

User session

This lightweight package provides helpers to manage user session.

Getting started

  1. Create a backend API to create & renew JWT sessions. It can be inspired or referenced from Plume Admin: https://github.com/Coreoz/Plume-admin/blob/master/plume-admin-ws/src/main/java/com/coreoz/plume/admin/webservices/SessionWs.java. Make sure OWASP considerations regarding JWT are correctly implemented.
  2. Create an API that implements the interface SessionRefresher. See below for an example.
  3. Create the User type that matches the JWT and that will be used in the project. See below for an example.
  4. A variant of the User type with the field exp can be optionally created in order to use a simpler User object through the project. See below for an example.
  5. Create the SessionService that will be used by component that will interact with the user sessions. See below for an example.
  6. Bind the services in the dependency injection system in the services-module.ts file. See below for an example.
  7. In index.tsx file, try to initialize the session at startup, and make sure local storage sessions are synchronized across different browser tabs See below for an example.
  8. Create some protected routes that will require a current user session. See below for an example.
  9. Create a page that will authenticate users. See below for an example.

Session API example

export type SessionCredentials = {
  userName: string,
  password: string,
};

export default class SessionApi implements SessionRefresher {
  constructor(private readonly httpClient: ApiHttpClient) {
  }

  authenticate(credentials: SessionCredentials) {
    return this
      .httpClient
      .restRequest<RefreshableJwtToken>(HttpMethod.POST, '/admin/session')
      .jsonBody(credentials)
      .execute();
  }

  refresh(webSessionToken: string) {
    return this
      .httpClient
      .restRequest<RefreshableJwtToken>(HttpMethod.PUT, '/admin/session')
      .body(webSessionToken)
      .execute();
  }
}

User type example

export type User = {
  idUser: string,
  userName: string,
  fullName: string,
  permissions: string[],
};

User type with expiration example

export type UserWithExpiration = User & {
  exp: number;
}

Session service example


const THRESHOLD_IN_MILLIS_TO_DETECT_EXPIRED_SESSION = 60 * 1000; // 1 minutes
const LOCAL_STORAGE_CURRENT_SESSION = 'user-session';
const HTTP_ERROR_ALREADY_EXPIRED_SESSION_TOKEN = 'ALREADY_EXPIRED_SESSION_TOKEN';

export default class SessionService {
  private jwtSessionManager: JwtSessionManager<UserWithExpiration>;

  constructor(
    private readonly sessionApi: SessionApi,
    private readonly scheduler: Scheduler,
    private readonly pageActivityManager: PageActivityManager,
    private readonly idlenessDetector: IdlenessDetector
  ) {
    this.jwtSessionManager = new JwtSessionManager<UserWithExpiration>(
      sessionApi,
      scheduler,
      pageActivityManager,
      idlenessDetector,
      {
        localStorageCurrentSession: LOCAL_STORAGE_CURRENT_SESSION,
        thresholdInMillisToDetectExpiredSession: THRESHOLD_IN_MILLIS_TO_DETECT_EXPIRED_SESSION,
        httpErrorAlreadyExpiredSessionToken: HTTP_ERROR_ALREADY_EXPIRED_SESSION_TOKEN,
      },
    );
  }

  // data access

  getSessionToken() {
    return this.jwtSessionManager.getSessionToken();
  }

  getCurrentUser() {
    return this.jwtSessionManager.getCurrentUser();
  }

  isAuthenticated() {
    return this.jwtSessionManager.isAuthenticated();
  }

  hasPermission(permission: Permission) {
    return this.jwtSessionManager.getCurrentUser().select((user) => user?.permissions.includes(permission) ?? false);
  }

  // actions

  authenticate(credentials: SessionCredentials) {
    return this
      .sessionApi
      .authenticate(credentials)
      .then((sessionToken) => this.jwtSessionManager.registerNewSession(sessionToken));
  }

  disconnect() {
    this.jwtSessionManager.disconnect();
  }

  tryInitializingSessionFromStorage() {
    this.jwtSessionManager.tryInitializingSessionFromStorage();
  }

  synchronizeSessionFromOtherBrowserTags() {
    this.jwtSessionManager.synchronizeSessionFromOtherBrowserTags();
  }
}

Services binding example

  // browser dependent services
  injector.registerSingleton(BrowserUserActivityListener, UserActivityListener);
  // other services
  injector.registerSingleton(IdlenessDetector);
  injector.registerSingleton(SessionService);

Project startup configuration example

In index.ts file:

const sessionService = injector.getInstance(SessionService);
sessionService.tryInitializingSessionFromStorage();
sessionService.synchronizeSessionFromOtherBrowserTags();

Protected routes example

<Routes>
<Route path="/login" element={<Login />} />
<Route
  path="/*"
  element={(
    <ConditionalRoute shouldDisplayRoute={sessionService.isAuthenticated()} defaultRoute="/login">
      <div id="main-layout">
        <Navigation />
        <div id="content-layout">
          <Header />
          <Router />
        </div>
      </div>
    </ConditionalRoute>
  )}
/>
</Routes>

Login page example

  // the session authentication API call
  const tryAuthenticate = (credentials: SessionCredentials) => {
    loader.monitor(sessionService.authenticate(credentials));
  };

  // check that the user is not already authenticated
  // => if that's the case, then skip the login page and display the authenticated page already! 
  const isAuthenticated = useObservable(sessionService.isAuthenticated());
  useOnDependenciesChange(() => {
    if (isAuthenticated) {
      navigate({ pathname: HOME });
    }
  }, [isAuthenticated]);
  
  // return form onSubmit={tryAuthenticate}