Skip to content

bcrypt.compare() always return false even when it´s supposed to be true #1037

Open
@s-pl

Description

Hello, I'm working on an authentication system in MongoDB. When storing passwords, everything seems fine:
{"_id":{"$oid":"66408f417315a786f0d1d279"},"username":"test","email":"[email protected]","password":"$2b$10$e2KuxFiAq4oVl7DaL80TX.9udp65K9uoiVOSfXZNmzHP8rVqIR5bG","role":"user","createdAt":{"$date":{"$numberLong":"1715507009424"}},"updatedAt":{"$date":{"$numberLong":"1715507009424"}},"__v":{"$numberInt":"0"}}
But then, when comparing the hash with the password, it always returns incorrect (even when it's correct). This is the method I'm using:

userSchema.pre('save', async function (next) {
  const user = this;
  if (!user.isModified('password')) return next();

  try {
    const salt = await bcrypt.genSalt();
    user.password = await bcrypt.hash(user.password, salt);
    next();
  } catch (error) {
    return next(error);
  }
});

userSchema.methods.comparePassword = async function (password) {
    
    console.log(password,this.password)
    return bcrypt.compare(password, this.password);
  
};

And this is the comparison log:
test $2b$10$e2KuxFiAq4oVl7DaL80TX.9udp65K9uoiVOSfXZNmzHP8rVqIR5bG

I think there's an error in the bcrypt.compare function, but I'm very lost

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions