【问题标题】:Hashing password before update a user in mongoose在猫鼬中更新用户之前散列密码
【发布时间】:2019-05-31 01:51:35
【问题描述】:

我创建用户,散列他的密码并保存在 mongo 上。当我尝试更新该用户时,我的问题就开始了。目前,当我更新哈希时不会生成,因为我真的不知道该怎么做。

获取我所说的用户的中间件:

exports.userByID = function(req, res, next, id) {
  User.findOne(
    {
      _id: id
    },
    function(err, user) {
      if (err) {
        return next(err);
      } else {
        req.user = user;
        next();
      }
    }
  );
};

用户控制器,用于更新用户:

exports.update = async function(req, res, next) {

  User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {
    if (err) {
      return next(err);
    } else {
      res.json(user);
    }
  });
};

用户模型的预“保存”:

UserSchema.pre("save", function(next) {

  var user = this;

  if (user.password) {

    var md5 = crypto.createHash("md5");
    user.password = md5.update(user.password).digest("hex");
    console.log("Password após o save (hasheando):" + user.password);
  }

  next();
});

我正在使用护照身份验证(“本地”)。已经在控制器更新上尝试过user.save()

user.save();
res.json(user);

但是,没有成功。

【问题讨论】:

  • 你在等待user.save()吗?
  • 这听起来可能很愚蠢,但您确定该值没有更新吗?您是在数据库中签入,还是仅在控制器中通过res.json() 返回值?另外,你的 pre('save') 函数是否被调用了?
  • 请不要使用 md5 进行密码散列。蛮力是far too easy。尝试谷歌搜索 argon2 或让 a module 处理散列
  • 感谢您的提示。我将使用另一个哈希

标签: node.js mongodb mongoose passport.js


【解决方案1】:

这可能是因为您没有将 new_password 存储在 mongo 中。

update controller 你必须这样做:

User.findByIdAndUpdate(req.user.id, req.body, function (err, user) {
  if (err) {
    return next(err);
  } else {
    user.password = req.body.new_password;
    user.save(function (err, user) {
      if (err) {
        res.send("Error: ", err);
      } else {
        res.send("password updated successfully!");
      }
    })
  }
});

【讨论】:

  • 像魅力一样工作!谢谢
  • 这是完美的解决方案
  • 这可能不是一个好的选择,因为你正在运行两个分开的东西。 findByIdAndUpdate 会将原始密码保存到您的数据库中。然后,您将使用散列密码运行另一个保存。可能很危险
【解决方案2】:

在保存密码之前,只需将其散列并在数据库中更新。如下所示。

 exports.update = async function(req, res, next) {
  let { body} = req;
  if(body['password']){
    var md5 = crypto.createHash("md5");
    body['password']= md5.update(body['password']).digest("hex");
  }
  let updateUser = await User.findByIdAndUpdate(req.user.id, body)
};

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 2020-12-20
    • 2017-03-08
    • 2019-12-29
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多