0

I am new to node js, I am trying to validate a password that is encrypted, and I have given the below code which I have tried.

async function passCheck(event) {
  // in event i am passing user entered password and email
  var EnteredPassword = bcrypt.hashSync(event.password, 10); //10 saltrounds

  var fromDB = await pool.query('SELECT password from User WHERE email  = ?', event.emailID);
  if (EnteredPassword == fromDB) {
    //Here i am comparing
    console.log('valid');
  } else {
    console.log('invalid');
  }
}
felixmosh
  • 32,615
  • 9
  • 69
  • 88
kp97338
  • 29
  • 2
  • 10

2 Answers2

1

bcrypt has a built-in method for comparing hashes.

async function passCheck(event) {
  var fromDB = await pool.query('SELECT password from User WHERE email  = ? Limit 1', event.emailID);
  // --------------------------------------------------------------------------^
  // Added limit 1 to make sure the only one record will be returned.
  if (fromDB.length > 0 && await bcrypt.compare(event.password, fromDB[0].password)) {
    //Here i am comparing
    console.log('valid');
  } else {
    console.log('invalid');
  }
}

DB result sets usually returns an array of objects, therefore, you should check that there are some results (fromDB.length > 0) and then pass to the compare method the hashed string itself.

felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • I think some of the cause for the question is OPs assumption that they can just compare 2 hashes for verification, like with md5. So maybe it has to be pointed out that this compare function can only compare plaintext + hash, but not hash + hash – kasoban Jan 27 '21 at 14:04
  • "errorMessage": "data and hash arguments required", – kp97338 Jan 27 '21 at 14:06
  • Check what value do you have in fromDB, and pass the password hash as the second argument – felixmosh Jan 27 '21 at 15:52
  • 1
    i replaced fromDB[0].password to fromDB[0][0].password now it is working thank you. – kp97338 Jan 27 '21 at 16:39
0

try this

  const auth = await bcrypt.compare(EnteredPassword , fromDB)
if(auth ){    
   console.log("valid");
}
else{
   console.log("invalid")

}

log ark
  • 11
  • 1
  • 3