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

cig3rfwq  于 8个月前  发布在  Postman
关注(0)|答案(1)|浏览(103)

我有个很奇怪的问题我正在为一个Web应用程序构建身份验证功能;注册登录使用Mongodb和bcrypt一切都在按预期进行;在Postman中,我可以注册一个新用户,让他们登录,并访问public和auth only路由(分别是logged out和logged in),以确保它按预期工作。我不得不将所有内容都移动到不同的目录和不同的代码库中,从那时起,每次尝试登录时,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条目x1c 0d1x

uxhixvfz

uxhixvfz1#

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

相关问题