Saap Lal
Saap Lal

Reputation: 1

encrypt/decrypt password using bcryptjs in node

I am trying to encrypt my password field i a registration form I created using bcryptjs but it isn't working

In mongodb, on post the data from the form, the password field shows the password entered in the form instead of encrypting it

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: `Name can't be empty`
  },
  username: {
    type: String,
    required: `Username can't be empty`
  },
  email: {
    type: String,
    required: `Email can't be empty`,
    unique: true
  },
  password: {
    type: String,
    required: `Password can't be empty`,
    minLength: [6, 'Password must be at least 6 character long']
  },
  saltSecret: String
});

userSchema.pre('save', (next)=>{
  bcrypt.genSalt(10, (err, salt)=>{
    bcrypt.hash(this.password, salt, (err, hash)=>{
      this.password = hash;
      this.saltSecret = salt;
      next();
    });
  });
});

Upvotes: 0

Views: 350

Answers (1)

Saap Lal
Saap Lal

Reputation: 1

I came up with the answer. I was using arrow function which doesn't have its own this binding. So I tried using the normal functions and it worked. The modified code:

userSchema.pre('save', function(next) {
  var user = this;
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(user.password, salt, function(err, hash) {
      user.password = hash;
      user.saltSecret = salt;
      next();
    });
  });
});

Upvotes: 0

Related Questions