Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash password on create and update

Tags:

sequelize.js

I am trying to hash a password for users when the record is created and when the user updates their password. On creation, I can do something like

User.beforeCreate((user, options) => {
  user.password = encryptPassword(user.password)
})

Which will be easily executed and hash the password for new users. But I have an issue when updating the password. If I just do

User.beforeUpdate((user, options) => {
  user.password = encryptPassword(user.password)
})

then everytime users updating their record (i.e update name, address, etc) it triggers the hook and re-hash the password.

How can I tell when the password is changed so that I can trigger the hook? Also instead of having those 2 hooks, how can I just use beforeSave to achieve the same result?

UPDATE

As per requested my User definition is as simple as

sequelize.define(
  'user',
  {
    id: {
      type:          Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey:    true,
    },
    emailAddress: {
      field:        'email_address',
      type:         Sequelize.STRING,
      allowNull:    false,
      unique:       true,
      validate: {
        isEmail: {
          args:     true,
          msg:      "Email is not valid"
        }
      },
    },
    password: {
      type:         Sequelize.STRING,
      allowNull:    false,
      validate: {
        min: {
          args:     6,
          msg:      "Password must be more than 6 characters"
        }
      }
    }
  }
)
like image 608
spondbob Avatar asked Jan 04 '23 16:01

spondbob


1 Answers

Hey there let me give this a shot

So first off you can run the same function for both hooks similar to below:

function encryptPasswordIfChanged(user, options) {
  if (user.changed('password')) {
    encryptPassword(user.get('password'));
  }
}

User.beforeCreate(encryptPasswordIfChanged);
User.beforeUpdate(encryptPasswordIfChanged);

When you want to change the password in your update and create API endpoints, you can just call user.set('password', somePasswordString);. I'm not exactly sure if that is exactly what you need but I think this pattern should do what you need. The .changed function should return true when you are creating the user because the _previousDataValues for the password should be undefined.

Good luck :)

like image 151
Dylan Aspden Avatar answered Jan 13 '23 13:01

Dylan Aspden