@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 lengthtokenExpirationTime
– duration of the login session (token life)userCustomSchema
– custom Mongoose Schema which will expand default user schemasecret
– 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 roleUSER
and aboveauth.accessLevel.admin
– restricts access to user roleADMIN
and aboveauth.accessLevel.superadmin
– restricts access to user roleSUPERADMIN
auth.accessLevel.selfOrAdmin
– restricts access to current user (as inreq.user
provided viaauth.jwt
) or user roleADMIN
and aboveauth.accessLevel.selfOrSuperadmin
– restricts access to current user (as inreq.user
provided viaauth.jwt
) or user roleSUPERADMIN
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);
});