首页 > 解决方案 > 无法在平均堆栈中散列密码

问题描述

这是来自路由文件的代码。

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

标签: mongodbexpressmongoosepassport.jsmean-stack

解决方案


为了解决您需要修复 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 Change Password

这是库文档:Bcrypt Nodejs


推荐阅读