当我尝试比较时 Bcrypt 密码失败?

问题描述

我是一个完整的编码初学者,目前正在学习 NodeJs,我已经被这种情况困扰了好几天了。 我正在尝试将 mongodb 中的散列密码与通过邮递员输入的用户进行比较。 我正在使用 bcrypt 将散列密码与原始字符串进行比较,但我得到了错误的陈述。 非常感谢任何帮助

这是猫鼬模型架构,

const useRSSchema = new mongoose.Schema({
  name: {
    type: String,required: true,trim: true,},email: {
    type: String,unique: true,lowercase: true,validate(value) {
      if (!validator.isEmail(value)) throw new Error("Invalid email");
    },password: {
    type: String,minLength: 7,validate(value) {
      if (value.toLowerCase().includes("password")) {
        throw new Error("Password should not consist of string 'password'.");
      }
    },})

在这里,我在保存到数据库之前对密码进行哈希处理;

useRSSchema.pre("save",async function (next) {

  const user = this;
  const saltRounds = 8;

  if (user.isModified("password")) {
    user.password = await bcrypt.hash(user.password,saltRounds);
  }

  next();
});

以下是登录路径;

router.post("/users/login",async (req,res) => {
  try {
    const user = await Users.findByCredentials(
      req.body.email,req.body.password
    );

    res.send(user);
  } catch (error) {
    res.status(400).send(error);
  }
});

下面是我尝试比较密码的地方,请帮助我找出错误的原因。

useRSSchema.statics.findByCredentials = async (email,password) => {
  const user = await Users.findOne({ email: email });

  if (!user) {
    throw new Error("Unable to log in!");
  }

  const isMatch = await bcrypt.compare(password,user.password);

  if (!isMatch) {
    throw new Error("Unable to login");
  }

  return user;
};

解决方法

尝试使用 bcryptjs.hashSync() 和 bcryptjs.compareSync 代替