2010-11-14 94 views
0

假设我有一个用户域类,字段为usernamepassword。为了简单起见,我想将密码存储为SHA-512散列。我也想在哈希之前验证密码,但在保存密码之前也要透明地哈希密码。有没有办法在域对象中做到这一点?保存Grails域名修改

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

不要说:

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

,我不能验证的散列

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 
} 

GORM Events我已经想出了以下内容:

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

现在这个工作当创建新用户时,ks很好。但是,如果我创建一个用户,给他们一个密码并保存它们,然后更改密码并重新保存这些方法都不会被调用,并且存储普通测试密码。

+1

我不知道为什么没有使用验证和'password'场二传手 - 感觉就像所有的域逻辑。 – 2011-05-21 06:25:58

+0

仅供参考,链接已损坏。现在http://gorm.grails.org/6.0.x/hibernate/manual/#eventsAutoTimestamping。 – 2017-08-04 10:11:27

回答

1

使用GORM Events

在保存或更新事件,你可以做创建哈希

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

完美!非常感谢你。 – 2010-11-14 00:18:24

+0

其实也许不完美。我会更新这个问题。 – 2010-11-14 04:32:37

+0

想通了,我不得不在'save()'调用中添加'flush:true'。 – 2010-11-14 04:46:12