将密码哈希化到路由文件中并更新

时间:2018-07-14 16:59:44

标签: express mongoose passport.js mean-stack

这是PUT的方法,我想对我的密码(使用护照)进行哈希处理并更新它。

router.put('/reset/:token', function(req, res) {
    console.log('listening');
  User.findOneAndUpdate({resetPasswordToken:req.params.token},{
    password: req.body.password,
    resetPasswordToken: undefined,
    resetPasswordExpires: undefined
  },function(err,user) {
    if(err) {
      console.log(err + 'is here');
    } else {
      res.json(user);
    }
  });
    });

我只想使用变量password。如何在此方法中进行哈希处理然后更新它。

1 个答案:

答案 0 :(得分:0)

我假设您正在使用Mongoose。首先,在您的pre内创建一个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);

然后在您的路线上:

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);
        });
    });
});