JWT登录发布请求返回不正确的密码错误

问题描述

当前,我的项目正确接收了注册请求,并将电子邮件和加密的密码存储到我的MongoDB数据库中。但是,当我使用与注册时相同的电子邮件和密码时,会收到一条错误消息,告诉我密码不正确

我已设置以下登录请求:

module.exports.login_post = async (req,res) => {
  // shows us the data that was sent.
  // console.log(req.body)
  // destructure to just get the email and password from the body

  const { email,password } = req.body;
    console.log('login called')
  try {
    const user = await User.login(email,password);

    // creates and sends a jwt cookie
    const token = createtoken(user._id);
    res.cookie("jwt",token,{ httpOnly: true,maxAge: maxAge * 1000 });

    res.status(200).json({ user: user._id });
  } catch (err) {
    const errors = handleErrors(err);
    res.status(400).json({ errors });
  }

  console.log(email,password)
  res.send('user login')
};

在此代码中,我引用从我的用户模型导入的User.login

userSchema.statics.login = async function (email,password){
  const user = await this.findOne({ email });
  if(user){
    const auth = await bcrypt.compare(password,user.password)
    if(auth){
      return user
    }
    throw Error('incorrect password')
  }
  throw Error('incorrect email')

}

现在,我可以注册用户,但是当我转身并在邮递员中使用相同的登录名和密码时,我的User.login函数收到错误错误密码”。

在这一点上,我不确定在解决问题时应该采取什么步骤。有没有办法console.log我尝试登录的密码的加密版本,以便确保已设置Bcrypt来正确加密用户密码?

编辑:请求我的注册码:

module.exports.signup_post = async (req,res) => {
  // destructure to just get the email and password from the body
  const { eMail,password } = req.body;
  // console.log(email,password)

  // add a try catch block

  try {
    const user = await User.create({
      eMail,password,words: [

      ]
    });
    const token = createtoken(user._id);
    res.cookie("jwt",maxAge: maxAge * 1000 });
    // (max age is in seconds and this take milliseconds)
    res.status(201).json({ user: user._id });
  } catch (err) {
      console.log(err)
    const errors = handleErrors(err);
    // console.log(err);
    res.status(400).json({ errors });
  }

  res.send('new signup')
};

第二次编辑:这是我的中间件,在保存新用户和加密密码之前会被触发

// hash passwords using SALT
userSchema.pre('save',async function (next){
  const salt = await bcrypt.genSalt()

  this.password = await bcrypt.hash(this.password,salt)

  console.log(this.password)
  next()
})

解决方法

使用下面的代码作为密码,将您的chnage saltRounds与您的bcrypt盐轮进行比较,它将与数据库中的密码进行比较

const comparePassword = (hashedPassword,password) => {
    return bcrypt.compareSync(password,hashedPassword);
}; 

let validations = {
    comparePassword,}

module.exports = validations;