@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})
});