Matheus Bernardi
Matheus Bernardi

Reputation: 151

Bcrypts compare and authenticate function authenticate any password

I'm using bcrypt to authenticate the users in my system. When i register an user, with the code:

UserSchema.pre("save", async function(next) {

 var user = this;

 if (user.isModified('password')) {

  var salt = bcrypt.genSaltSync(10);

  await bcrypt.hash(user.password, salt, null, function(err, hash) {
   if(err){
    console.log(err);
   }else {
    user.password = hash;
   }      
  });

 }

 next();
});

Ok, the hash is created and save in mongo. My problema is, when i log in with this user, any password works. Here's is my compare function:

UserSchema.methods.authenticate = async function(password) {

 var user = this;

 var isAuthenticaded = await bcrypt.compare(password, user.password, 
 function(err, res){
  if(res){
   return true;
  }else{
   return false;
  }
 });

 return isAuthenticaded;
};

I call the function 'authenticate' with passport:

if (!user.authenticate(password)) {
 return done(null, false, {message: 'Senha inválida.'});
}

Someone could help?

[EDIT] - I think the problem is asynchronous calls. Modified to syncrhonous and it works! I will apreciate if someone discover where is the problem with asyncrhonous calls

Upvotes: 0

Views: 38

Answers (1)

Grynets
Grynets

Reputation: 2525

About async implementation.

UserSchema.pre('save', async function save(next) {
  if (!this.isModified('password')) return next();

  try {
   const salt = await bcrypt.genSalt(10);
   this.password = await bcrypt.hash(this.password, salt);
   return next();
  } catch (err) {
   return next(err);
  }
});

UserSchema.methods.authenticate = async function(password) {
   return bcrypt.compare(password, this.password);
};

And now, if user using our async authentication method, we have to await for result.

if (!await user.authenticate(password)) {
  return done(null, false, {message: 'Senha inválida.'});
}

You can read more about pre.

Upvotes: 1

Related Questions