1

I am trying to validate a user's password using bcryptjs. I have this function which returns a Promise, however when I get to bycrypt.hash, all i get is Promise { <pending> } Therefore .then() will not execute on undefined. Please help, I've been stuck on this a while

userSchema.methods.verifyPassword = function (password, err, next) {
  const saltSecret = this.saltSecret;
  const a = async function(resolve, reject) {
    console.log('hi4')
    console.log('this.saltSecret2', saltSecret);
    console.log(password);

    const hashed_pass = await bcrypt.hash(password, saltSecret);
    console.log('hash', hashed_pass);
    const valid = await bcrypt.compare(password, hashed_pass);
    if(valid){
      console.log('GOOD');
    }
  };
  a();
};
Jonathan
  • 441
  • 1
  • 9
  • 28
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! You forgot to resolve your promise when the hash was computed but not good. – Bergi Jan 31 '20 at 02:45
  • `resolve(false);` when `hash == this.password` returns false. – hoangdv Jan 31 '20 at 02:56

3 Answers3

3

I like to use async-await syntax to handle promises. It is less confusing. and gives the ability of quickly understanding someone else code.

you can make your function an async one. wait until bcrypt does its job

const password = await bcrypt.hash(password, saltSecret);

However bcrypt library provides a function to compare password and the hash

const valid = await bcrypt.compare(password, hashed_pass);

try this

async function(resolve, reject) {
  console.log('hi4')
  console.log(this.saltSecret);
  console.log(password);

  const hashed_pass = await bcrypt.hash(password, saltSecret);
  console.log('hash', hashed_pass);
  const valid = await bcrypt.compare(password, hashed_pass);
  if(valid){
    console.log('GOOD');
  }
};
Dulara Malindu
  • 1,477
  • 4
  • 18
  • 37
1

This line will always return a Promise.

console.log(bcrypt.hash(password, this.saltSecret));

You could always do something like this.

return new Promise(async (resolve, reject) => {
    const hash = await bcrypt.hash(password, this.saltSecret);

    if (hash == this.password) {
        return resolve(true);
    }

    return reject();
});
0

bcrypt.hash uses a callback, not a promise (that's what the .then is doing)

You should use it like so:

bcrypt.hash(password, this.saltSecret, (err, hash) => {
    ...
});
Adam Smith
  • 357
  • 4
  • 13