简体   繁体   中英

Grails Domain modification on save

Say I have a user domain class with fields username and password . For simplicity say I would like to store the passwords as a SHA-512 hash. I also want to validate the password prior to hashing it, but also transparently hash the password before saving it. Is there a way to do this in the domain object?

static constraints = 
{
    username(blank: false, unique: true);
    password(minSize: 10);
}

Instead of saying:

def user = new User(username: "joe", password: createHash("joepass"));

where I can't validate the hash

def user = new User(username: "joe", password: "joepass");
if(user.validate())
{
    user.save(); // Would then turn password into a hash on save
}
else
{
    // Handle validation errors
}

Following GORM Events I've come up with the following:

def beforeInsert = { doHash(); }
def beforeUpdate = { doHash(); }
void doHash()
{
    if(this.password.size() != 32)
    {
        this.password = this.password.encodeAsHash(); // I wrote a codec for this
    }
}

Now this works fine when creating new users. However, if I create a user, give them a password, and save them, then change the password and re-save neither of these methods gets called and the plain test password gets stored.

Use the GORM Events

On the save or update events you can do the create hash

   def beforeInsert = {
       // do hash magic
   }
   def beforeUpdate = {
        // do hash magic
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM