npm.io
5.1.1 • Published 1 year ago

@travetto/auth-rest-session

Licence
MIT
Version
5.1.1
Deps
5
Size
5 kB
Vulns
0
Weekly
0
Stars
23

Rest Auth Session

Rest authentication session integration support for the Travetto framework

Install: @travetto/auth-rest-session

npm install @travetto/auth-rest-session

# or

yarn add @travetto/auth-rest-session

One of Rest Auth's main responsibilities is being able to send and receive authentication/authorization information from the client. This data can be encoded in many different forms, and this module provides the ability to encode into and decode from the user's REST Session context. This module fulfills the contract required by Rest Auth of being able to encode and decode a user principal by storing the user principal in the session.

The SessionPrincipalEncoder is exposed as a tool for allowing for decoding/encoding principals into the session.

Code: SessionPrincipalEncoder

import { Injectable, Inject } from '@travetto/di';
import { FilterContext } from '@travetto/rest';
import { Principal } from '@travetto/auth';
import { PrincipalEncoder } from '@travetto/auth-rest';
import { SessionService } from '@travetto/rest-session';

/**
 * Integration with the auth module, using the session as a backing
 * store for the auth principal.
 */
@Injectable()
export class SessionPrincipalEncoder implements PrincipalEncoder {
  #key = '_trv_auth_principal'; // Must be serializable, so it cannot be a symbol

  @Inject()
  service: SessionService;

  encode(_: FilterContext, p: Principal): void {
    const session = this.service.get();
    if (p) {
      p.expiresAt = session.expiresAt; // Let principal live as long as the session
      session.setValue(this.#key, p);
    } else {
      session.destroy(); // Kill session
    }
  }

  async decode({ req }: FilterContext): Promise<Principal | undefined> {
    const session = await this.service.get(); // Preload session if not already loaded
    return session?.getValue<Principal>(this.#key);
  }
}

As you can see, encode and decode just read and write from the session context. The main feature here, is that if the authentication expires, the session should be destroyed. Additionally, the user's expiry time is assumed to live as long as the session for simplicity's sake.

Keywords