bcrypt 比较登录时与任何密码不匹配

问题描述 投票:0回答:1

我有一个很奇怪的问题。我正在为网络应用程序构建身份验证功能;注册、登录。这是使用 mongodb 和 bcrypt。一切都按预期进行;在 Postman 中,我可以注册一个新用户,将其登录,并访问公共和仅限身份验证的路由(分别注销、登录),以确保其按预期工作。我必须将所有内容移动到不同的目录以及不同的代码存储库,从那时起,每次我尝试登录时,似乎

bcrypt.compare()
都会失败,即使我可以确认用户已成功添加到数据库中。我已经通过差异检查器运行了相关文件,以查看是否有任何更改,但无法识别任何主要差异,希望有人能有一些见解。包括注册和登录的路由,以及下面的用户模型;如果需要更多上下文,我会添加更多。

登记路线

app.post('/register', (request, response) => {
  bcrypt.hash(request.body.password, 10)
    .then((hashedPassword) => {
      const user = new User({
        email: request.body.email,
        password: hashedPassword,
      });

      user
        .save()
        .then((result) => {
          response.status(201).send({
            message: 'User created successfully',
            result,
          });
        })
        .catch((error) => {
          response.status(500).send({
            message: 'Error creating user',
            error,
          });
        });
    })
    .catch((error) => {
      response.status(500).send({
        message: 'Password was not hashed successfully',
        error,
      });
    });
});

登录路线

app.post('/login', (request, response) => {
  User.findOne({ email: request.body.email })
    .then((user) => {
      bcrypt.compare(request.body.password, user.password)
        .then((passwordCheck) => {
          if (!passwordCheck) {
            return response.status(400).send({
              message: 'Password does not match',
              error,
            });
          }

          const token = jwt.sign(
            {
              userId: user._id,
              userEmail: user.email,
            },
            'RANDOM-TOKEN',
            { expiresIn: '24h' }
          );

          response.status(200),send({
            message: 'Login Successful',
            email: user.email,
            token,
          });
        })
        .catch((error) => {
          response.status(400).send({
            message: 'Password does not match',
            error,
          });
        });
    })
    .catch((error) => {
      response.status(404).send({
        message: 'User not found',
        error,
      });
    });
});

用户模型

const mongoose = require("mongoose");

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    required: [true, "Please provide an Email!"],
    unique: [true, "Email Exists"],
  },

  password: {
    type: String,
    required: [true, "Please provide a password!"],
    unique: false,
  },
});

module.exports = mongoose.model.Users || mongoose.model("Users", UserSchema);

Postman 选项卡/结果,Mongo 条目

mongodb mongoose postman bcrypt
1个回答
0
投票

我认为这是一个盐问题,因为你说你更改了存储库,所以我认为 bcrypt 无法获得相同的盐,因此它失败了。检查您是否已正确配置。

© www.soinside.com 2019 - 2024. All rights reserved.