express和mongoose的新密码不正确

svmlkihl  于 2023-02-23  发布在  Go
关注(0)|答案(1)|浏览(287)

我想实现一个更新用户密码的控制器。

    • 问题:**创建用户时,我在数据库中看到它已正确散列。当我尝试控制器(更新密码)时,我发送旧密码和新密码。

第一次运行正常。但是,如果我把新的放进旧的,然后设置一个新的,我会得到错误:"消息":"旧密码不正确"。为什么?
我的控制器:

module.exports.updatePassword = async (req, res) => {
  const { userId } = req.params;
  const { oldPassword, newPassword } = req.body;

  try {
    const user = await User.findById(userId);

    const isPasswordValid = await user.isValidPassword(oldPassword);

    if (!isPasswordValid) {
      return res.status(401).json({ message: "Incorrect old password" });
    }

    const salt = await bcrypt.genSalt(10);
    const newHashedPassword = await bcrypt.hash(newPassword, salt);
    const oldHashedPassword = user.password;

    if (oldHashedPassword === newHashedPassword) {
      return res
        .status(400)
        .json({
          message: "New password should not be the same as old password",
        });
    }

    user.password = newHashedPassword;
    await user.save();

    return res.json({ message: "Password updated successfully" });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: "Server error" });
  }
};

我的用户架构:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, "Provide an email."],
    unique: true,
    match: [
      /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,
      "Please, provide a valid email.",
    ],
  },
  password: {
    type: String,
    required: [true, "Password is required."],
  },
  firstname: {
    type: String,
    required: [true, "Firstname is required."],
  },
  lastname: {
    type: String,
    required: [true, "Lastname is required."],
  },
});

UserSchema.pre("save", async function (next) {
  const user = this;
  const salt = await bcrypt.genSalt(10);
  const hash = await bcrypt.hash(user.password, salt);
  user.password = hash;
  next();
});

UserSchema.methods.isValidPassword = async function (password) {
  const user = this;
  const compare = await bcrypt.compare(password, user.password);

  return compare;
};

module.exports = mongoose.model("User", UserSchema);
zf9nrax1

zf9nrax11#

你已经在pre保存hook中散列了密码,所以你不需要在updatePassword路径中再次散列它。
因此,将user.password = newHashedPassword;更改为user.password = newPassword;应该可以解决该问题。

相关问题