2

this is my code for hashing password and for compare existing password into existing module with a password that has been sended on body request:

        //hash password of document that use this schema
    bcrypt.hash(user.password, null, null, function (err, hashed) {

        if (err) {
            throw err;
        } else {
            user.password = hashed;

            //next api
            next();
        }
    })
});

userSchema.methods.comparePassword = function (password) {

    //refer at userSchema
    var user = this;

    //return method of bcryot library that compare two string: original password and password hashed
    return bcrypt.compareSync(password, user.password);

};

But compare this error message:

Uncaught, unspecified "error" event. (Not a valid BCrypt hash.)

2 Answers 2

2

Resolved !!! Into the database i have a lot of user's password not hashed and when i try to login, with bcrypt.compareSync (password, user.password); it expected that has been hashed password.

Sign up to request clarification or add additional context in comments.

Comments

1

You're using null twice. I'd wager that you've wrapped this function inside the bcrypt.genSalt function(if you haven't , do so). You need to pass it the bcrypt salt where the first null is written.

Here's a full example:

userSchema.pre('save', function (next) {
  const SALTROUNDS = 10;  // or another integer in that ballpark
  const user = this;
  if(!user.isModified('password')) {
    return next();
  }

  bcrypt.genSalt(SALTROUNDS, (err, salt) => {
    if (err) { return next(err); }

    bcrypt.hash(user.password, salt, null, (error, hash) => {
      if (error) { return next(error); }

      user.password = hash;
      next();
    });
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.