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

@enlighten1/auth

v1.0.14

Published

ENLIGHTEN Authentication module

Downloads

20

Readme

@enlighten1/auth

This is open source auth module used in ENLIGHTEN Node.js backend projects

Instalation

npm i @enlighten1/auth

Basic usage

In index.js:

const auth = require('@enlighten1/auth');

Optionally pass config and initialize:

const auth = require('@enlighten1/auth');

const authConfig = {
    passwordMinLength: 8,

    tokenExpirationTime: '12h',

    userCustomSchema: {
        customField: {
            type: String,
            default: 'some string from main config',
        },
    },
};

auth.configure(authConfig);

Config options:

  • passwordMinLength – password minimal length
  • tokenExpirationTime – duration of the login session (token life)
  • userCustomSchema – custom Mongoose Schema which will expand default user schema
  • secret – secret for signing JWT Tokens

User roles

This module uses three user roles in accountType field:

  • USER
  • ADMIN
  • SUPERADMIN

Authorization middlewares

Module provides two authorization middlewares:

  • auth.jwt – middleware on all routes which should be restricted after login with Bearer Token (JWT)
  • auth.local – middleware used on login route

Middleware auth.jwt sets current user (based on JWT) to req.user (as Passport.js).

Example:

router.post('/login', auth.local, async function (req, res) {
    // Login business logic, login function described below
});

router.get('/only-logged-in', auth.jwt, async function (req, res) {
    // your code here...
    console.log(req.user); // Displays user info
});

Access level middleware

Module also provides some access level checkers middleware which must be used with auth.jwt authorization middleware:

  • auth.accessLevel.user – restricts access to user role USER and above
  • auth.accessLevel.admin – restricts access to user role ADMIN and above
  • auth.accessLevel.superadmin – restricts access to user role SUPERADMIN
  • auth.accessLevel.selfOrAdmin – restricts access to current user (as in req.user provided via auth.jwt) or user role ADMIN and above
  • auth.accessLevel.selfOrSuperadmin – restricts access to current user (as in req.user provided via auth.jwt) or user role SUPERADMIN

Example:

router.get(
    '/my-endpoint-only-for-admins',
    auth.jwt,
    auth.accessLevel.admin,
    async function (req, res, next) {
        // your code here...
    }
);

Functions

  • handleUserRegister
  • handleLogin
  • handleWhoAmI
  • handleUpdatePassword
  • handleGetAllUsers
  • handleGetUser
  • handleUpdateUser
  • handleDeleteUser
  • token.handleResetPasswordInit
  • token.handleTokenVerification
  • token.handleTokenUsageAndSetNewPassword
  • get.allUsers
  • get.singleUser
  • update.singleUser

Getters & modifiers & creators

Module provides getters and modifiers for some custom business logic related to users data models.

⚠️ Warning: theese functions should be used with caution only on secured endpoints (with access level middleware) in order to prevent user data leakage!

const allUsers = await auth.get.allUsers();
const singleUser = await auth.get.singleUser(userId);
const updatedUser = await auth.update.singleUser(userId, data);
const newUser = await auth.create.singleUser(userData);

Events

Module emits events in specific actions. List of events and their sample payload is described below:

auth_register

{
    eventType: 'auth_register',
    date: 1623238325492,
    user: {
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 0,
        _id: '60c0a6b5b7a3b66290ba0298',
        created: 1623238325445,
        __v: 0
    }
}

auth_login

{
    eventType: 'auth_login',
    date: 1623238353772,
    user: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_update_password

{
    eventType: 'auth_update_password',
    date: 1623238506929,
    user: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_update_user

{
    eventType: 'auth_update_user',
    date: 1623238644054,
    user: {
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        _id: '60c0a6b5b7a3b66290ba0298',
        created: 1623238325445,
        __v: 0
    },
    userBeforeChange: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    },
    userAfterChange: {
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        _id: '60c0a6b5b7a3b66290ba0298',
        created: 1623238325445,
        __v: 0
    }
}

auth_delete_user

{
    eventType: 'auth_delete_user',
    date: 1623238985713,
    user: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_password_reset_init

{
    eventType: 'auth_password_reset_init',
    date: 1623240104653,
    user: {
        username: '[email protected]',
        hash: '$2b$08$vfSao9YStk/PGSsB4yGzHeAX6.5mTUbgIdWN0jdtCwwBLgavcmv/2',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623239241312,
        _id: 60c0aa33ce22db63dc100a3b,
        created: 1623239219591,
        __v: 0
    },
    token: {
        userId: 60c0aa33ce22db63dc100a3b,
        dateCreated: 1623240104608,
        dateUsed: null,
        tokenString: 'TqQ1qCXTilGQ1ef0CxsPY8A5f9Rcj6Td',
        action: 'PASSWORD_RESET',
        isActive: true,
        _id: 60c0ada8aa119f646822d273,
        __v: 0
    },
    tokenString: 'TqQ1qCXTilGQ1ef0CxsPY8A5f9Rcj6Td'
}

auth_perform_password_reset

{
    eventType: 'auth_perform_password_reset',
    date: 1623242292206,
    user: {
        _id: 60c0aa33ce22db63dc100a3b,
        username: '[email protected]',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623239241312,
        created: 1623239219591,
        __v: 0
    }
}

Full endpoints implementation

In your /users router add theese endpoints:

const auth = require('./auth');

////////////////////////////////////////////////////////////////
// User registration & authorization

router.post('/', async function (req, res) {
    await auth.handleUserRegister(req, res, EventBus);
});

router.post('/login', auth.local, async function (req, res) {
    await auth.handleLogin(req, res, EventBus);
});

router.get('/whoami', auth.jwt, async function (req, res) {
    await auth.handleWhoAmI(req, res);
});

router.put('/:userId/password', auth.jwt, auth.accessLevel.selfOrAdmin, async function (req, res) {
    await auth.handleUpdatePassword(req, res, EventBus);
});

////////////////////////////////////////////////////////////////
// User basic CRUD

router.get('/', auth.jwt, auth.accessLevel.admin, async function (req, res) {
    await auth.handleGetAllUsers(req, res);
});

router.get('/:userId', auth.jwt, auth.accessLevel.selfOrAdmin, async function (req, res) {
    await auth.handleGetUser(req, res);
});

router.put('/:userId', auth.jwt, auth.accessLevel.selfOrAdmin, async function (req, res) {
    await auth.handleUpdateUser(req, res, EventBus);
});

router.delete('/:userId', auth.jwt, auth.accessLevel.selfOrSuperadmin, async function (req, res) {
    await auth.handleDeleteUser(req, res, EventBus);
});

////////////////////////////////////////////////////////////////
// Tokens & password reset

router.post('/reset-password/init/:email', async function (req, res) {
    await auth.token.handleResetPasswordInit(req, res, EventBus);
});

router.get('/reset-password/validate-token/:token', async function (req, res) {
    await auth.token.handleTokenVerification(req, res);
});

router.post('/reset-password/finish/:token', async function (req, res) {
    await auth.token.handleTokenUsageAndSetNewPassword(req, res, EventBus);
});