Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 我尝试比较时Bcrypt密码失败?_Node.js_Bcrypt - Fatal编程技术网

Node.js 我尝试比较时Bcrypt密码失败?

Node.js 我尝试比较时Bcrypt密码失败?,node.js,bcrypt,Node.js,Bcrypt,我是一个完全的编码初学者,目前正在学习NodeJs,我被这种情况困扰了好几天。 我试图将mongodb中的散列密码与用户通过postman输入的密码进行比较。 我使用bcrypt将散列密码与原始字符串进行比较,但得到的却是错误的语句。 非常感谢您的帮助 这是猫鼬模型模式 const usersSchema = new mongoose.Schema({ name: { type: String, required: true, trim: true, }, e

我是一个完全的编码初学者,目前正在学习NodeJs,我被这种情况困扰了好几天。 我试图将mongodb中的散列密码与用户通过postman输入的密码进行比较。 我使用bcrypt将散列密码与原始字符串进行比较,但得到的却是错误的语句。 非常感谢您的帮助

这是猫鼬模型模式

const usersSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
    lowercase: true,
    validate(value) {
      if (!validator.isEmail(value)) throw new Error("Invalid email");
    },
  },
  password: {
    type: String,
    required: true,
    trim: true,
    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相反

我想知道,如何保存和更新用户。您的“save”钩子有一个问题。“save”钩子不会在update和findOneAndUpdate上执行。因此,当更新密码时,它不会被散列。您应该使用其他钩子,如
updateOne
findOneAndUpdate
。我已经尝试将钩子findOne更改为findOneAndUpdate,但结果仍然是相同的false。而且似乎bcrypt每次都生成不同的哈希,即使我输入相同的字符串。因此,在比较之前,这将永远不会匹配。只需将console.log
password
user.password
进行比较,并确保这些值是您期望的值。这样你可以缩小问题的范围是的,这些值是不同的,不明白为什么
console.log(user.password)
/$2a$08$hnfxw2ws.jznauegxrty.mlrfcwjkatwb/a580lbeu51gvzbzvyi
console.log(wait bcrypt.hash(password,8))
/$2a$08$7fd4nhw6lv2absmcf7n20oyvgugzslfukafqymevytu6jw