1.0.14 • Published 3 years ago

@enlighten1/auth v1.0.14

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

@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: 'aa@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 0,
        _id: '60c0a6b5b7a3b66290ba0298',
        created: 1623238325445,
        __v: 0
    }
}

auth_login

{
    eventType: 'auth_login',
    date: 1623238353772,
    user: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: 'aa@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_update_password

{
    eventType: 'auth_update_password',
    date: 1623238506929,
    user: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: 'aa@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_update_user

{
    eventType: 'auth_update_user',
    date: 1623238644054,
    user: {
        username: 'aa1@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        _id: '60c0a6b5b7a3b66290ba0298',
        created: 1623238325445,
        __v: 0
    },
    userBeforeChange: {
        _id: 60c0a6b5b7a3b66290ba0298,
        username: 'aa@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    },
    userAfterChange: {
        username: 'aa1@bb.cc',
        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: 'aa1@bb.cc',
        facebookId: null,
        accountType: 'USER',
        lastLogin: 1623238353679,
        created: 1623238325445,
        __v: 0
    }
}

auth_password_reset_init

{
    eventType: 'auth_password_reset_init',
    date: 1623240104653,
    user: {
        username: 'aa@bb.cc',
        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: 'aa@bb.cc',
        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);
});
1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago

0.0.2

3 years ago

0.0.1

3 years ago