DNN
DNN

Reputation: 871

Can't change property of this

I was trying to create a custom save method so as not to store user passwords as plain text. But it seems whatever I do to change the value of this.values doesn't have any effect. This is my sequelize model:

module.exports= function (sequelize, DataTypes){
return sequelize.define("Users",{
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    email: DataTypes.STRING,
    is_admin: DataTypes.BOOLEAN,
    active: DataTypes.BOOLEAN
},{  instanceMethods: {
    user_save: function(){
        if(this.isNewRecord){
            var salt = 'blahblahblah';
            var key128Bits = CyrptoJS.PBKDF2(this.values.password, salt, { keySize: 128/32 });
            delete this.values.password;
            this.values.password = key128Bits.toString()
            console.log('new record ' + key128Bits.toString())
        }
        console.log(this.values)
        this.save();
        return
    }}
  }
);};

the first log statement confirms that the code inside the if isNewRecord is running, and generating a hash, the second log statement and the output indicate that the properties of this remain unchanged from their original values. Does anyone know why this is or how I can fix the problem?

I could do this immediately after a post request but I'd rather do it this way if possible.

Upvotes: 0

Views: 191

Answers (2)

sdepold
sdepold

Reputation: 6241

The thing is that this.values is actually only a getter which returns all the attributes with its respective values. It might be a good idea to add also a setter. But then there is the question if the setter should update the database or not. So basically this.values should only be used for stuff like console.log. Also it's used internally for instance.toJSON().

And as XMen already answered correctly, you have to use this.password instead of this.values.password :)

Upvotes: 1

XMen
XMen

Reputation: 30248

http://sequelizejs.com/#instances-update-save

set this.password instead of this.values.password

Upvotes: 1

Related Questions