【问题标题】:unable hash the password in mean stack无法在平均堆栈中散列密码
【发布时间】:2018-12-25 01:49:21
【问题描述】:

这是路由文件中的代码。

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".

【问题讨论】:

  • 哈希对创建新用户有用吗?如果没有,您可能希望使用该 bcrypt-nodejs 模块而不是 bcrypt 模块,如下面的答案中所述。我也遇到了bcrypt 模块的一些问题。
  • 是的,它有效。我已经解决了。
  • 太棒了! :) 您可以编辑您的原始帖子以提供问题的答案,以防其他人遇到与passport 类似的问题。

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


【解决方案1】:

为了解决问题,你需要修复你的 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

【讨论】:

    猜你喜欢
    • 2018-11-29
    • 1970-01-01
    • 2023-03-22
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多