mongoose 错误:Node.js和MongoDB的电子邮件/密码组合无效

gpfsuwkq  于 2023-02-04  发布在  Go
关注(0)|答案(1)|浏览(129)

我试图登录我的管理员,我定义了登录凭据都在mongodb和.env所以这里的代码有一个问题。

const Admin = require('../models/admin');
const Voters = require('../models/voters');
const bcrypt = require('bcrypt');

exports.checkCredentials = async (req, res, next) => {
  const email = req.body.email;
  const password = req.body.password;

  Admin.findOne({ email: email }).exec(async (error, adminData) => {
    if (error) {
      // some error occured
      return res.status(400).json({ error });
    }
    if (adminData) {
      // email is correct checking for password
      const match = await bcrypt.compare(password, adminData.password);
      if (match) {
        req.adminID = adminData._id;
        next();
      } else {
        return res.status(200).json({
          msg: 'Invalid email/password combination yyy',
        });
      }
    } else {
      // no data found for given email
      return res.status(200).json({
        msg: 'Invalid email/password combination !!!!',
      });
    }
  });
};

exports.verifyVoter = async (req, res, next) => {
  let query;
  if (req.query.voterID) {
    query = {
      voterID: req.query.voterID,
    };
  } else {
    query = {
      phone: req.body.phone,
    };
  }
  console.log(query);
  Voters.findOne(query).exec(async (error, voterData) => {
    if (error) {
      // some error occured
      return res.status(400).json({ error });
    }
    if (voterData) {
      // Voter found
      if (voterData.hasRegistered === true) {
        return res.status(200).json({
          msg: 'Voter already registered',
        });
      } else {
        req.phone = voterData.phone;
        req.district = voterData.pinCode;
        req._id = voterData._id;
        next();
      }
    } else {
      // no data found for given Voter
      return res.status(200).json({
        msg: 'Invalid VoterID',
      });
    }
  });
};

上面的代码带来了一个错误,但这是我在.env中定义管理员凭据的方式

ADMIN_EMAIL = bkroland19@gmail.com
ADMIN_PASSWORD =felinho/013

这就是我在mongodb中定义它们的方式

{
    "email": "bkroland19@gmail.com",
    "password": "felinho/013"
}

这是导致的错误,我得到的电子邮件正在输入匹配这两个电子邮件。任何帮助,请
当我输入mongodb数据库中的凭据时,我希望能够登录

57hvy0tb

57hvy0tb1#

如果您以明文存储密码,则不需要bcrypt.compare

const match = password === adminData.password;
if (match) {
  req.adminID = adminData._id;
  next();
}

无论如何,强烈建议加密它们,您可以使用以下命令:

const salt = await bcrypt.genSalt(12);
const encryptedPassword = await bcrypt.hash(password, salt);

const user = await Admin.create({ email, password: encryptedPassword });

相关问题