Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a hashed password with validation in Waterline?

The Waterline docs give an example of using beforeCreate to hash a password. That works great unless you have validation on the password field and you try to update the record. Here's my snipped example:

types: {
    hasUpperCase: function (value) {
        return value.search(/[A-Z]/) != -1;
    },
    hasLowerCase: function (value) {
        return value.search(/[a-z]/) != -1;
    },
    hasNumber: function (value) {
        return value.search(/[0-9]/) != -1;
    }
},
attributes: {
    password: {
        type: 'string',
        minLength: 8,
        hasUpperCase: true,
        hasLowerCase: true,
        hasNumber: true
    }, 
    salt: {
        type: 'string'
    },
    // ...
}
beforeCreate: function (values, next) {
    // Encrypt the password and record the salt.
    psalty.createHash(values.password)
        .then(function (psalt) {
            values.password = psalt.hash;
            values.salt = psalt.salt;
            next();
        })
        .done(null, next);
},

When I come to update the record I get a validation error, something like:

{"password":[
    {"rule":"hasUpperCase","message":"\"hasUpperCase\" validation rule failed for input: 'b7d58848e4eb40ec78e756d1302ef7aeb628841a40273d2465713d2231faab396669ec7bdab91c75eaf999064cfc9c3110b1211f24fbab626619730dcadfaee069b58cb4b64e6b57d1ba7c73c22d683eb783f04439c5b0d198b56d52c219c4eab35bd7b0d56696242f4be0ac70082d6dafc65d6d2f578b22ad292582fb973f'"}]
}

So there are a couple of issues here.

The first is that when the record is saved to update another field (let's say it's a User table and they are changing their profile information), the current hash must remain intact.

The second issue is when and existing user wants to update their password in an existing record, we need to be able to rehash the password.

Has anyone using Sails or Waterline standalone come up with good model strategies to deal with these types of situations? My assumption is that I'm going to have to move validation to one of the event handlers.

Thanks in advance.

like image 794
Andrew Eddie Avatar asked Oct 21 '22 04:10

Andrew Eddie


1 Answers

Check this file:

https://github.com/vimia/sails-core/blob/master/api/models/User.js

You will put the salt with the password ...

like image 67
Marcelo Boeira Avatar answered Oct 23 '22 02:10

Marcelo Boeira