I'm on the final step of my password reset workflow and am experiencing a weird issue where the code runs successfully, prints out my artist document as well as the words "Successfully resubmitted password".
Then, without stopping, runs a second time and prints out null for artist and flashes error "Password reset token is invalid or has expired".
Confusing part
The new password doesn't take but the variables resetPasswordToken and resetPasswordExpires are both set to null, just like the success part of the if statement requests.
Reset password function
const bcrypt = require('bcrypt');
module.exports.submitNewPassword = async (req, res) => {
const slidedHeaderToken = req.headers.referer.slice(-40);
const artist = await Artist.findOne({ resetPasswordToken: slidedHeaderToken, resetPasswordExpires: { $gt: Date.now() } });
console.log(artist);
if (!artist) {
req.flash('error', "Password reset token is invalid or has expired");
res.render('artists/reset')
} else {
const hashedPassword = bcrypt.hashSync(req.body.password, 12)
artist.password = hashedPassword;
artist.resetPasswordToken = null;
artist.resetPasswordExpires = null;
artist.save();
console.log("Successfully resubmitted password");
req.flash('success', "Successfully resubmitted password, please login with your updated credentials");
res.redirect('login');
}
}
Route
const passport = require('passport');
router.route('/reset/:token')
.get( artists.renderPasswordReset)
.post( catchAsync (artists.submitNewPassword ))
In my app, artists are users but not sure if I need to clarify that somewhere for passport or bcrypt.
Any ideas what's going on with my code and why 2/3 of it works?