簡體   English   中英

保存時修改Grails域

[英]Grails Domain modification on save

假設我有一個用戶域類,其中包含usernamepassword字段。 為了簡單起見,我想將密碼存儲為SHA-512哈希。 我還想在對密碼進行哈希處理之前先對其進行驗證,而且還要在保存之前透明地對密碼進行哈希處理。 是否可以在域對象中執行此操作?

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活動之后,我提出了以下建議:

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

現在,這在創建新用戶時可以正常工作。 但是,如果我創建一個用戶,給他們一個密碼,然后保存它們,然后更改密碼並重新保存,則不會調用這兩種方法,也不會存儲普通測試密碼。

使用GORM事件

在保存或更新事件上,您可以創建哈希

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM