I'm assuming you are using Mongoose
. First, create a pre
method inside your Schema
.
UserSchema
const mongoose = require('mongoose')
, bcrypt = require('bcrypt-nodejs')
, SALT_WORK_FACTOR = 10;
const UserSchema = new mongoose.Schema({
... // schema here
});
/**
* Hash password with blowfish algorithm (bcrypt) before saving it in to the database
*/
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password'))
return next();
user.password = bcrypt.hashSync(user.password, bcrypt.genSaltSync(SALT_WORK_FACTOR), null);
next();
});
mongoose.model('User', UserSchema);
And then in your route:
router.put('/reset/:token', function(req, res, next) {
User.findOne({resetPasswordToken: new RegExp('^' + req.params.token + '$', "i")}, function (err, user) {
if (err)
return next(err);
if (!user)
return res.status(422).json({errors: [{msg: 'invalid reset token'}]});
user.resetPasswordToken = '';
user.resetPasswordExpires = '';
user.password = req.body.password;
user.save().then(function (user) {
return res.status(200).json(user);
});
});
});