PicoYou
PicoYou

Reputation: 71

Node js - Bcrypt - compare method returns false for the correct input password

I've been through various similar questions here and i tried them all, but still, the result is always "wrong password".

I'm using bcrypt for nodejs and my password hashes are stored in an Postgresql database.

The hash and compare methods are as follow :

generateHash : function(password, callBack){

    bcrypt.genSalt(8, function(err, salt) {

        bcrypt.hash(password, salt, callBack);
    });
}

validPassword : function(password, callBack){

    bcrypt.compare(password, this.password, callBack);
}

I'm using these function in the following piece of code :

//Generating hashing and DB storing
User.generateHash(password, function(err, hash) {

    // if there is no user with that email
    // create the user
    var newUser = User.build({

        email: email,
        password: hash
        })
        .save()
        .then(function(newUser) {

            return done(null, newUser);
        })
        .catch(function(err){

            return done(err, false);
        });
   });

//...
//Checking the password input for login

user.validPassword(password, function(err, res) {

     if(err) throw err;

     if(!res){

         return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); 
     }
     else{

         // all is well, return successful user
         return done(null, user);
     }
});

I hope that was clear. Thanks in advance. Ciao.

Update I : callBack added to validPassword, although this didn't fix the problem. And i have also checked the this.password value, it's correct and as expected. So, the problem is still present.

Upvotes: 1

Views: 870

Answers (2)

PicoYou
PicoYou

Reputation: 71

i just solved the problem. lol it was a series of errors that made this hard to figure it out. So i'm just going to enumerate what must be done to avoid such things :

  1. The hash must be stored in the database as a varchar and not as a char. The latest cause the hash to be of a non correct length, and so the comparison will fail. varchar is the solution to this.
  2. Handling the comparison result must be done inside of the callBack function. This is due to nodejs being asynchronous. This was correct (see code in the question) i just want to point it out. Otherwise, the result of the comparison would be undefined.

I hope this will help some of you.

Upvotes: 1

leroydev
leroydev

Reputation: 2945

I think you forgot to add callBack as parameter to

validPassword : function(password){

Try if adding that solves your problem, so change it to

validPassword : function(password, callBack){

Also, I don't know where your validPassword function is in, but you might want to check if this.password does indeed refer to the users password.

Upvotes: 1

Related Questions