javascript - Mongoose changes password every time I save with pre-save hook -
i'm using pre-save hook bcrypt encrypt passwords on system. works fine when creating or changing password. problem seems re-encrypt password every time change , save different field, example e-mail.
probably easier explain code. here's model:
const userschema = new schema({ email: { type: string, required: true, lowercase: true, unique: true, trim: true }, password: { type: string, required: true } })
and hook:
userschema.pre('save', function(next){ const user = this; console.log(user); bcrypt.gensalt(10, function(err, salt){ if (err){ return next(err) } bcrypt.hash(user.password, salt, null, function(err, hash){ if(err){return next(err)} user.password = hash; next(); }) }) });
and here's code update e-mail address:
module.exports = function(req, res){ user.findone({ _id: req.body.user}, function(err, doc){ if(err){ console.log(err); return; } doc.email = req.body.data; doc.save(function(err, returndata){ if (err){ console.log(err); return; } res.send(returndata); }) }) }
so when call doc.save
in final example, updates e-mail address intended re-encrypts password, meaning if user logs out, can't log in again.
can how around this?
try this:
userschema.pre('save', function(next){ if (!user.ismodified('password')) return next(); const user = this; bcrypt.gensalt(10, function(err, salt){ if (err){ return next(err) } bcrypt.hash(user.password, salt, null, function(err, hash){ if(err){return next(err)} user.password = hash; next(); }) }) });
Comments
Post a Comment