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 Ev开发者_高级运维ents 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
}
精彩评论