bcrypt.compare returning false even with correct password after certain period of time

Asked

Viewed 366 times

0

I’m using the bcrypt to generate password hash in Node.js, as code below, after creating a user:

UserSchema.pre("save", async function(next) {
  const hash = await bcrypt.hash(this.pass, 8);
  this.pass = hash;
  next();
});

However, when logging in, the verification function uses the method compare of bcrypt, and after a while, starts to return false even being with the correct password, at first it works, but when passing a few hours, sometimes days, stop returning true and returns false. The verification code is below:

let userExists = await User.findOne({ name });
  if (userExists) {
      const password = await bcrypt.compare(pass, userExists.pass);
      if(password) console.log(password);
  }

Can anyone tell me if there’s an inconsistency with the bcrypt? I’m using version 2.4.3.

For testing, I created a user named 'a' with password '123456' and its generated hash was $2a$08$M.WZbdMKOFjPCQBp0iYAf.cENIWvMV.4efgCqWPjwoXrIP97Iv.Fm, returned true in a period of 3 hours, after that, starts to return false with the same password.

I created other users, some took days to return false. But there’s always this mistake, a time to work.

  • This package is very stable I use it! must be something in your code.

1 answer

0


I suggest this edition:

userSchema.pre('save', async function () {
  if (this.isModified('password')) {
    this.password = await User.hash(this.password)
  }
})
userSchema.statics.hash = function(password) {
  return bcrypt.hash(password, 10)
}
userSchema.methods.matchesPassword = function(this, password) {
  return bcrypt.compare(password, this.password)
}
// ...
const user = await User.findOne({ email })
if (!(await user.matchesPassword(password))) {
    throw new Error('Senha Incorreta')
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.