Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

How to add validations for generated properties #67

Open
ericchaves opened this Issue · 1 comment

2 participants

@ericchaves

Hi guys,

I've created a generated property in my resource to encrypt password. basically what I'm doing is:

User.string('password').required(true);
User.property('password', 'string', {
  get:function () {
        console.log(this.properties.password);
    return this.properties.password;
  },
  set:function (value) {
        if (typeof value !== 'undefined' && value !== null){
            this.properties.password_salt = bcrypt.genSaltSync(12);
            value = bcrypt.hashSync(value, this.password_salt);
        }
    return this.properties.password = value;
  }
});

This way I can create a user calling User.create({username: 'user', password: '12345') and have it encrypted by immediately. What I'd like now is have this property required and also apply some schema validations like minimumLength. is this possible?

The required(true) as above does not seem to have any effect.

Thanks for any help,

Eric

@robert52

@ericchaves,

You can just do:

User.property('password', 'string', {
  set:function (value) {
        if (typeof value !== 'undefined' && value !== null){
            this.properties.password_salt = bcrypt.genSaltSync(12);
            value = bcrypt.hashSync(value, this.password_salt);
        }
    return this.properties.password = value;
  },
  required: true,
  restricted: true
});

remove the "get" part will cause a "Maximum call stack size exceeded", had no time to look into this problem.
note on restricted, prevents listing of attributes when you call ".safeJSON"
also you can do something like this:

User.string('password', { required: true, restricted: true, set: encryptPassword });

The problem with all this is that the password is hashed everytime when you create, save or update the User, also the password will be double hashed when you use User.create();

Robert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.