Home > other >  Why bcrypt.compareSync() always return false?
Why bcrypt.compareSync() always return false?

Time:04-14

I try to check if both passwords coincide before the user makes a change in the profile.

  1. The first one is saved in the database like this when the user was registered:

    bcrypt.hashSync(req.body.pass, 8)

  2. And the second one is the password that the user sent as a request

This is the way I try to compare it:

var passwordIsValid = bcrypt.compareSync(
    req.body.pass,
    user.pass // the result of searching the user in my database
);

but passwordIsValid is always false, despite the strings being the same

CodePudding user response:

This might help, This is how I use bcrypt with mongoose to hash my password and compare:

/* eslint-disable import/prefer-default-export */
import mongoose from 'mongoose';
import {
  hash as _hash,
  compareSync
} from 'bcrypt-nodejs';
import mongooseDelete from 'mongoose-delete';

const {
  Schema
} = mongoose;

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  gender: {
    type: String,
    enum: ['male', 'female'],
  },
  profilePicture: {
    type: String
  },
  password: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    unique: true,
    required: true,
  },
}, {
  timestamps: true
}, );

UserSchema.plugin(mongooseDelete);

// hash the password before the user is saved
UserSchema.pre('save', function hashPassword(next) {
  // hash the password only if the password has been changed or user is new
  if (!this.isModified('password')) {
    next();
    return;
  }

  // generate the hash
  _hash(this.password, null, null, (err, hash) => {
    if (err) {
      next(err);
      return;
    }

    // change the password to the hashed version
    this.password = hash;
    next();
  });
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function comparePassword(password) {
  const data = compareSync(password, this.password);
  return data;
};

export {
  UserSchema,
};

Hope this helps :)

  • Related