53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
/**
|
|
* Utils
|
|
*/
|
|
|
|
const bcrypt = require(`bcryptjs`);
|
|
|
|
/**
|
|
* Build a custom error
|
|
* @param {string} message Error message
|
|
* @param {number} code Error code, should be HTTP status code
|
|
*/
|
|
const customError = (message = "An error occurred.", code = 500) => {
|
|
const error = new Error(message);
|
|
error.code = code;
|
|
return error;
|
|
};
|
|
|
|
/**
|
|
* Build a custom validation error
|
|
* @param {array[string]} validationErrors Validation errors
|
|
*/
|
|
const validationError = (validationErrors = []) => {
|
|
let error = new Error("Validation error(s)");
|
|
error.validationErrors = validationErrors;
|
|
error.code = 400;
|
|
return error;
|
|
};
|
|
|
|
/**
|
|
* Hash password
|
|
* @param {string} password Password to hash
|
|
*/
|
|
const hashPassword = (password) => {
|
|
const salt = bcrypt.genSaltSync(10);
|
|
return bcrypt.hashSync(password, salt);
|
|
};
|
|
|
|
/**
|
|
* Compare password
|
|
* @param {string} candidatePassword Hashed password supplied by user
|
|
* @param {string} trustedPassword Hashed password on record for user
|
|
*/
|
|
const comparePassword = (candidatePassword, trustedPassword) => {
|
|
return bcrypt.compareSync(candidatePassword, trustedPassword);
|
|
};
|
|
|
|
module.exports = {
|
|
customError,
|
|
validationError,
|
|
hashPassword,
|
|
comparePassword,
|
|
};
|