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

authogonal

v1.0.0-alpha1

Published

Typescript Authentication

Downloads

1

Readme

Authogonal

Typescript Client Authentication Library

Authogonal provides functionality for authenticated web service access, managing login and tokens that allow SPA to work seamlessly with back end authenticated requests.

It is designed primarily to easily integrate with an event based state management UI (e.g. react with redux). The implementation is framework agnostic, to allow any side-effect managment style to be used (e.g. thunks, sagas, or observables).

Quick Start

The following is a quick start example with a redux set up.

State Management

An action handler is provided to handle the authentication state.

import * as Authogonal from 'authogonal';

// Set an authentication slice on the app state
export interface AppState {
    authentication: AuthenticationState;
    /* rest of the app state*/
}

// Set the provided handler on the reducer
const rootReducer = combineReducers({
    authentication: Authogonal.handleAuthAction,
    /* Other app reducers */
});

// Create redux store
const reduxStore = createStore(rootReducer, ... middleware ...);

Side effects

The side effect management depends on the framework used (e.g. thunks, or observables). Helper classes and functions are provided to enable integration with whatever side effect management style is used.

import * as Authogonal from 'authogonal';

// create the access manager using the provided builder, with required services
const accessManager = Authogonal.newAccessManagerBuilder<AppUser>()
  .setPasswordLoginService(passwordLoginService)
  .setTokenLoginService(tokenLoginService)
  .setUserService(userService)
  .build();

// If using redux thunk, you can use the provided action creator
const actionCreator = new Authogonal.AuthogonalActionCreator(accessManager);
actionCreator.setAsyncRefreshEventDispatcher(dispatch);
const onLogin = async (userId: string, password: string): Promise<boolean> => {
  const loginCredentials = Authogonal.createLoginCredentials({ userId, password,remember: true});
  const loginThunk = actionCreator.createManualLoginAction(loginCredentials)
  return await dispatch(loginThunk);
}

// For redux-observable, set up epics using provided callback converters
accessManager.setAsyncRefreshEventCallback(dispatch);
const onManualLogin = (action$: Observable<Authogonal.PerformManualLoginAction>) => {
    return action$.pipe(
        ofType(Authogonal.PERFORM_MANUAL_LOGIN),
        switchMap(event => {
            return new Observable<Authogonal.ManualLoginActions<AppUser>>(observer => {
                accessManager.manualLogin(event.credentials, Authogonal.observerToManualLoginCallback(observer));
            })
        })
    );
}
const rootEpic = combineEpics(
    onRefreshRequired,
    onManualLogin
)

Request enrichment

API requests can be enriched with authorization tokens using the supplied request enrichers. For example, with SuperAgent

const request = Request.post(uri).send(body);
const response = await accessManager.requestEnricher.enrich(request);

Documentation

The main interface to the authentication library is the AccessManager and the Request Enricher.

interface AccessManager {
    readonly requestEnricher: RequestEnricher<TRequest>;
    // these should be called as side-effects by dispatching events
    silentLogin(eventCallback: SilentLoginCallback<TUser>): Promise<boolean>;
    manualLogin(credentials: UserCredentials, eventCallback: ManualLoginCallback<TUser>): Promise<boolean>;
    logout(eventCallback: LogoutCallback): Promise<void>;
    // this should be called with the dispatcher for any direct async calls (e.g. timer that refreshes tokens) 
    setAsyncRefreshEventCallback(eventCallback: SilentLoginCallback<TUser>): void;
    // this can be called when you know that a refresh is required (e.g. if a request returns a 403)
    onAccessExpired(eventCallback?: SilentLoginCallback<TUser>): Promise<boolean>;  
}

export interface RequestEnricher<R> {
  authorizeRequest(request: R): Promise<R>;
}

These methods and event callbacks allow you to call authentication functionality, and forward authentication events, via your particular side-effect management implementation.

The request enricher supplements back end requests with appropriate authentication once a user has been authenticated (e.g. using auth tokens)

API services


import { AuthenticatorResponse, LogoutInfo, UserAuthenticator, UserCredentials, UserCredentialsDefinition } from "./user-authenticator";

declare module './user-authenticator' {
    export interface UserCredentialsDefinition {
        bespoke: { name: string }
    }
}

export class BespokeAuthenticator<U> implements UserAuthenticator<U> {
    authenticate(userCredentials: UserCredentials): Promise<AuthenticatorResponse<U>> {
        if (userCredentials.credentialType === 'bespoke') {

        }
        throw new Error("Method not implemented.");
    }

Token Lifecycle

  • On start up, check tokens
    • Access token is unexpired then attempt to get user details
      • if successful then consider as logged in.
      • if auth exception then atttempt with refresh token
    • Refresh token is unexpired, then try and refresh access token
      • if successful then get user details and consider as logged in
      • if exception then attempt with remember me token
    • Remember me token exists and unexpired, try to refresh with this token
      • if successful then get user details and consider as logged in
      • if exception then need to log in
  • User logs in with username and password
  • Access token, refresh token (and optionally remember me token) stored
  • When access token expires, request a new one via the refresh token.
  • When refresh token expires, try with remember me token, or force a log in