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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wizim-dev/auth

v0.0.2

Published

Authentification module

Readme

Auth

Authentification module.

Getting Started

To use this module in your project, install the npm package

npm install '@snark/auth'

Usage

import Auth from '@snark/auth'

const api = express.Router();
const configuration = {
    findUser: function (username) {
        return db.collection('user').findOne({username});
    },
    updateUser: function (user) {
        return db.collection('user').replaceOne({_id: user._id}, user)
            .then(result => result.modifiedCount === 1 ? user : null)
            .catch((err): any => {
                logger.error(err);
                return null;
            });
    }
}

const isAuthenticated = Auth(api, configuration);

api.get('/ping', isAuthenticated, function (req, res) {
    console.log('ony logged user can ping API!')
    res.json({success:true})
});

Configuration

The Auth module takes a few simple options, only findUser(username) method is required:

  • register: Boolean flag indicating whether to enable register route (default: true).
  • login: Boolean flag indicating whether to enable login route (default: true).
  • updatePassword Boolean flag indicating whether to enable update password route (default: true).
  • loginRoute: String indicating the url path to use for login route (default: '/auth/login').
  • registerRoute: String indicating the url path to use for register route (default: '/auth/register').
  • updatePasswordRoute String indicating the url path to use for update password route (default: '/auth/password').
  • passwordField: String indicating the field name to use in body payload to retrieve password (default: 'password').
  • usernameField: String indicating the field name to use in body payload to retrieve username (default: 'username').
  • newPasswordField String indicating the field name to use in body payload to retrieve new password (default: 'newPassword').
  • idField: String indicating the field name to use in user object gotten from getId(item, options) method (default: '_id').
  • secret: String indicating the secret key use to sign JWT (default: 'SecretKeySnark').
  • authExpire: Number indicating the token expiration value (default: 86400).
  • saltRounds Number indicating the salt rounds (default: 10).
  • findUser: Method to retrieve user object from DB required
  • getPassword: Method to retrieve password from body request.
  • getNewPassword: Method to retrieve new password from body request.
  • getUsername: Method to retrieve username from body request.
  • getId: Method to retrieve unique identifier from object gotten from findUser.
  • loginAfterRegister: Boolean flag indicating if the user is logged automatically when he register. (default false).
  • completeLoginData: Fonction appelée après un login avec le user et le body du login pour pouvoir agir et ajouter des choses au login existant si besoin.

getPassword(item, options)

Method to retieve password from item object (body request) Generate a bim.badData error if undefined

function getPassword(item, options) {
    return item && item[options.passwordField];
}

getNewPassword(item, options)

Method to retieve new password from item object (body request) Generate a bim.badData error if undefined

function getNewPassword(item, options) {
    return item && item[options.newPasswordField];
}

getUsername(item, options)

Method to retieve username from item object (body request) Generate a bim.badData error if undefined

function getUsername(item, options) {
    return item && item[options.usernameField];
}

getId(item, options)

Method to retieve id from item object (user object gotten from findUser(username)) Generate a bim.badImplementation if undefined or null

function getId(item, options) {
    return item && item[options.idField];
}

isAuthenticated

Middleware to check if an user is authenticated

import Auth from '@snark/auth'

const api = express.Router();
const configuration = {
    findUser: function (username) {
        return db.collection('user').findOne({username});
    },
    updateUser: function (user) {
        return db.collection('user').replaceOne({_id: user._id}, user)
            .then(result => result.modifiedCount === 1 ? user : null)
            .catch((err): any => {
                logger.error(err);
                return null;
            });
    }
}

const isAuthenticated = Auth(api, configuration);

api.get('/ping', isAuthenticated, function (req, res) {
    console.log('ony logged user can ping API!')
    res.json({success:true})
});

Errors

Auth module uses Bim module to handle errors

export enum AuthError {
    UserNotFound = 'Auth.User.NotFound',
    PasswordInvalid = 'Auth.Password.Invalid',
    NewPasswordInvalid = 'Auth.NewPassword.Invalid',
    TokenNotFound = 'Auth.Token.NotFound',
    TokenExpired = 'Auth.Token.Expired',
    TokenInvalid = 'Auth.Token.Invalid',
    UsernameFieldMissing = 'Auth.Username.required',
    PasswordFieldMissing = 'Auth.Password.required'
}

Some extra options:

tokenCanBeInQuery

If this option is true, the authentication middleware look for the token in the Authorization header (as usual), but if it doesn't find it, it look for a token query string.

fillUserMiddleware

If this option is true, the auth main function doesn't return just the isAuthenticated middleware but an object with :

{
    isAuthenticated:    the standard authentication middleware
    fillUserMiddleware: a middleware filling the req with the user if he's connected but without to send 401 
                        if the user is not connected (in this case, req.user is undefined)
}

tokenMode

By default, tokenMode is set to jwt and you don't have to worry about token storage. But in jwt mode there is some points:

  • A same user can be connected with two different browsers at the same time.

If you want to do differently, you have to set the tokenMode to database. In this mode, the token will be saved in the user profile in database and :

  • If a user login in a browser then in another browser, the token will be reseted and the first connection will be invalidated.

However, in this mode you should provide the two callbacks findUserWithToken and updateUserToken.

import Auth from '@snark/auth'

const api = express.Router();
const configuration = {
    tokenMode: "database",
    findUser: function (username) {
        return db.collection('user').findOne({username});
    },
    updateUser: function (user) {
        return db.collection('user').replaceOne({_id: user._id}, user)
            .then(result => result.modifiedCount === 1 ? user : null)
            .catch((err): any => {
                logger.error(err);
                return null;
            });
    },
    findUserWithToken: function (token) {
        return db.collection('user').findOne({token});
    },
    updateUserToken: function(userId, token, tokenExpire) {
        return db.collection('user').updateOne({_id: userId}, {
            $set: {
                token,
                tokenExpire
            }
        });
    }
}

const isAuthenticated = Auth(api, configuration);

api.get('/ping', isAuthenticated, function (req, res) {
    console.log('ony logged user can ping API!')
    res.json({success:true})
});