Checking Passwords If the user is found, we'll check the user's password next. We'll hash the password, then compare the resultant hash with the hash in the database. We can use the brcrypt.compare() method in order to do this. It accepts the password and the corresponding hash as arguments. This method performs the hash and compares it with the hash we pass as the second argument: // controllers/users.js module.exports.login = (req, res) => { const { email, password } = req.body; User.findOne({ email }) .then((user) => { if (!user) { return Promise.reject(new Error('Incorrect password or email')); } // comparing the submitted password and hash from the database return bcrypt.compare(password, user.password); }) .catch((err) => { res .status(401) .send({ message: err.message }); }); }; The bcrypt.compare() method works asynchronously so its result will be returned in a chained then() function. If the hashes match, then() with return true, otherwise, it will return false: // controllers/users.js module.exports.login = (req, res) => { const { email, password } = req.body; User.findOne({ email }) .then((user) => { if (!user) { return Promise.reject(new Error('Incorrect password or email')); } return bcrypt.compare(password, user.password); }) .then((matched) => { if (!matched) { // the hashes didn't match, rejecting the promise return Promise.reject(new Error('Incorrect password or email')); } // successful authentication res.send({ message: 'Everything good!' }); }) .catch((err) => { res .status(401) .send({ message: err.message }); }); };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter