使用NodeJs Mongo和Express在更新时保留哈希密码

时间:2018-08-13 08:49:56

标签: node.js mongodb express put

我正在尝试使用MEAN构建应用程序。在注册时,一切正常,将使用密码字段将用户引入数据库并验证哈希。但是在更新时,密码和验证不再散列,它们将作为纯文本添加到数据库中。我该如何解决? (我还没有前端代码,我使用Postman发送请求)

这是我现在拥有的:

model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt');

var schema = new Schema({
  firstname: { type: String, required: true },
  lastname: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true },
  verify: { type: String, required: true },
});

schema.pre('save', function (next) {
  var user = this;
  bcrypt.hash(user.password, 10, function (err, hash) {
    if (err) {
      return next(err);
    }
    user.password = hash;
    user.verify = hash;
    next();
  });
});

module.exports = mongoose.model('User', schema);

controller.js

var router = express.Router();

// register user
router.post('/register', function (req, res, next) {
  addToDB(req, res);
});  

async function addToDB(req, res) {
  var user = new User({
    firstname: req.body.firstname,
    lastname: req.body.lastname,
    email: req.body.email,
    password: req.body.password,
    verify: req.body.verify
  });

  try {
    doc = await user.save();
    return res.status(201).json(doc);
  }
  catch (err) {
    return res.status(501).json(err);
  }
}

// update user
router.put('/:id', function (req, res, next) {
  User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
    if (err) {
      console.log('Error in user update: ' + JSON.stringify(err, undefined, 2));
      return next(err);
    }
    res.json(post);
  });
});

1 个答案:

答案 0 :(得分:1)

更新您的Mongoose中间件,使其仅在例如已修改(或是新的)时对密码进行哈希处理。

if let question = reviewViewModel.datafordisplay(atindex: indexPath).question {
    cell.question.text = question
}

因为schema.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(); // generate a salt bcrypt.genSalt(10, function(err, salt) { if (err) return next(err); // hash the password along with our new salt bcrypt.hash(user.password, salt, function(err, hash) { if (err) return next(err); // override the cleartext password with the hashed one user.password = hash; user.verify = hash next(); }); }); }); findByIdAndUpdate的包装,所以最好使用save以便调用pre save钩子

findOneAndUpdate