2010-11-14 79 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