无法对均值堆栈中的密码进行哈希处理

时间:2018-07-17 11:15:05

标签: mongodb express mongoose passport.js mean-stack

这是路由文件中的代码。

router.put('/reset/:token', function(req, res, next) {
  console.log('reseting the password');
  User.findOne({resetPasswordToken:req.params.token}, 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.addUser(user, (err, user) => {
      if(err){
        res.json({success: false, msg:'password has not changed'});
      } else {
        res.json({success: true, msg:'password has changed'});
      }
    });
  });
});

这部分代码来自我的架构文件。

const UserSchema = mongoose.Schema({
  password: {
    type: String,
    required: true
  },

  resetPasswordToken: {
    type: String
  },
  resetPasswordExpires: {
    type: Date
  }

});

  const User = module.exports = mongoose.model('User', UserSchema);
module.exports.addUser = function(newUser, callback){
    bcrypt.genSalt(10, (err, salt) => {
      bcrypt.hash(newUser.password, salt, (err, hash) => {
        if(err) throw err;
        newUser.password = hash;
        newUser.save(callback);
      });
    });
  }

当我尝试保留密码时,密码将按照输入的提示进行存储。它没有对密码进行哈希处理。例如,我给了密码“ zp12345”,在数据库中它存储为"password" : "zp12345".

1 个答案:

答案 0 :(得分:0)

要解决此问题,您需要修复addUser方法:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

module.exports.addUser = function(newUser, callback){
    bcrypt.hash(newUser.password, bcrypt.genSaltSync(10), null, (err, hash) => {
       if (err) {
         return next(err);
       }
       newUser.password = hash;
       newUser.save(callback);
    })
};

还有另一个例子:Mongoose Pre Save Changing Password

这是图书馆文件:Bcrypt Nodejs