Authentication

Reference

This page explains the low level functions exposed by the library and is intended for advanced users and curious minds. In most cases you'll be leveraging the library through the generated code that wraps these functions and exposes a higher level API in the form of a express route handler.

Importing

import {
    init as authInit,
    getRequestHandler as auth
} from '@subzerocloud/auth';

Initializing

The init function takes 3 parameters:

  • a database client that will be used to run queries against the database (pg or better-sqlite3)
  • a nodemailer compatible object that will be used to send emails
  • a log function that will be used to log messages ( you'll probably want to log only in debug mode )
import nodemailer from 'nodemailer';
import debug from 'debug';

// when using postgresql as a database
import { Client } from 'pg';

// when using sqlite as a database
// import Client from 'better-sqlite3';

// you can also pass an already initialized sqlite client
// const db = new Client(connectionString);

//...
await authInit(Client, nodemailer,{
    logFn: debug('subzero:auth')
    // uncomment this line if you get the error:
    // "total length of command line and environment variables exceeds limit"
    // customEnv: env.parsed,
});

In case you need to use other database clients besides pg/better-sqlite3, the parameter can be any class providing it implements this type of interface:

class MyDbClient {
    constructor({connectionString}: {connectionString: string}) {
        // constructor implementation
    }

    async connect(): Promise<void> {
        // Implementation of the connect method
    }

    async query(text: string, values?: any[]): Promise<any> {
        // Implementation of the query method
    }

    async execute(text: string, values?: any[]): Promise<void> {
        // Implementation of the execute method
    }
}

Handling requests

const authHandler = auth();

The authHandler function has the following signature:

async function (req: Request | IncomingMessage, res: Response | ServerResponse, next?: NextFunction)

which means it can be used with Express or directly with Node.js http module or by passing Request and Response objects directly.

For a list of endpoint exposed by the library see here

Previous
Auth Library Overview