sequelize.js - hash password on create and update -


i trying hash password users when record created , when user updates password. on creation, can like

user.beforecreate((user, options) => {   user.password = encryptpassword(user.password) }) 

which executed , hash password new users. have issue when updating password. if do

user.beforeupdate((user, options) => {   user.password = encryptpassword(user.password) }) 

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

how can tell when password changed can trigger hook? instead of having 2 hooks, how can use beforesave achieve same result?

update

as per requested user definition 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 not valid"         }       },     },     password: {       type:         sequelize.string,       allownull:    false,       validate: {         min: {           args:     6,           msg:      "password must more 6 characters"         }       }     }   } ) 

hey there let me give shot

so first off can run same function both hooks similar below:

function encryptpasswordifchanged(user, options) {   if (user.changed('password')) {     encryptpassword(user.get('password'));   } }  user.beforecreate(encryptpasswordifchanged); user.beforeupdate(encryptpasswordifchanged); 

when want change password in update , create api endpoints, can call user.set('password', somepasswordstring);. i'm not sure if need think pattern should need. .changed function should return true when creating user because _previousdatavalues password should undefined.

good luck :)


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -