Reputation: 364
I'm trying to set set up an update function for user profiles on a Node.JS application with hash passwords using the bcrypt-nodejs module. It works when signing in, but when I am updating the profile it updates the user object with the plain text (i.e.: I type "text" for the password, the db shows "text"). I would like to hash the password when the profile is updated. How would I fix this?
Below is my code for the controller:
exports.editUser = function(req, res) {
// user edit form set to findonendupdate
User.findByIdAndUpdate({ _id: req.params.user_id, randString: req.body.randString }, req.body, function(err, user) {
if (err)
res.send(err);
res.json({ data: user });
});
};
For reference this is the user model code that works with a new user registration:
passport.use('local', new LocalStrategy(
function(username, password, callback) {
User.findOne({ username: username } , function (err, user) {
if (err) { return callback(err); }
// No user found with that username
if (!user) { return callback(null, false); }
// Make sure the password is correct
user.verifyPassword(password, function(err, isMatch) {
if (err) { return callback(err); }
// Password did not match
if (!isMatch) { return callback(null, false); }
// Success
return callback(null, user);
});
});
}
));
Upvotes: 2
Views: 6199
Reputation: 1688
I just solved by converting plain text password to hashed password before updating password.
req.body.password = await bcrypt.hash(req.body.password, 8);
await Admin.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
if (!err) {
req.flash('success', 'Admin Updated successfully!');
res.status(201).render('admin-views/admin/edit_admin', { success_message: req.flash('success'), admin: doc });
}
else {
res.render("admin-views/admin/edit_admin", {
admin: req.body
})
}
})
hope this code is works!
Upvotes: 0
Reputation: 34667
User.findByIdAndUpdate({...}, req.body, function(err,...
Here you're receiving the password in req.body
and telling it to update it directly as it is (plain text).
You need to hash it and then update
// retrieve the password field
var password = req.body.password
// update it with hash
bcrypt.hash(password, (hash) => {
req.body.password = hash
// then update
User.findByIdAndUpdate({...}, req.body, function(err,... // then update
});
Upvotes: 5