skip to Main Content

Here I was created one loginUser model which simply check if user is exists or not code is working fine but I am facing error in isValidPassword it will always false condition even if the email and password is true.

Whenever I try to console.log(isValidPassword) then it will return undefined and same case happening with validStatus

const express=require('express');
const bcrypt=require('bcrypt');
let salt;

const loginUser=async (req,res)=>{
       const {email,password}=req.body;
       try{
              let user=await userModel.findOne({email});
               salt= await bcrypt.genSalt(10);

              if(!user) return res.status(400).json("invalid Username or passowrd");
              
              let validStatus=false;
              let isValidPassword = await bcrypt.compare(password,user.password,(err,result)=>{
                     // console.log(err);
                     console.log(result);
                     if(result) validStatus=true;

              });
              console.log(validStatus);
              
              if(!isValidPassword) return res.status(400).json("invalid Username or passowrd");

              const token=createToken(user._id);
              res.status(200).json({_id:user.id,name:user.name,email,token});
       }
       catch(err)
       {
              console.log(err);
       }
};

2

Answers


  1. bcrypt.compare already returns a promise so dont pass calback to it

    Login or Signup to reply.
  2. You’re trying to use both a callback and a Promise from compare. Simply remove the callback from the compare call (see BCrypt with promises:

    let isValidPassword = await bcrypt.compare(password,user.password)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search