const config = require('@config/index') const bcrypt = require('bcrypt') const { toInt } = require('@libs/route-utils') /** * hash password func * @param {string} pass password string * @return {string} */ const hashPassword = async (pass = '') => { if (typeof pass !== 'string' || pass.trim().length === 0) return null let saltRound = toInt(config.salt_round, 1, 1) let passHash = await new Promise((resolve, reject) => { bcrypt.hash(pass, saltRound, (err, hash) => { if (err) { reject(err) return } resolve(hash) }) }) return passHash } /** * compare password and hash * @param {string} password password string * @param {string} hash hash string * @return {boolean} */ const comparePassword = async (password = '', hash = '') => { if (typeof password !== 'string' || password.trim().length === 0) return false if (typeof hash !== 'string' || hash.trim().length === 0) return false let check = await new Promise((resolve, reject) => { bcrypt.compare(password, hash, (err, res) => { if (err) { resolve(false) return } resolve(res) }) }) return !!check } module.exports = { hashPassword, comparePassword }