2012-07-02 25 views

回答

2

對我來說,你在你的gorm對象中驗證的應該是你保存的東西。如果您想驗證未編碼的密碼,那麼我建議您創建一個command object,並在密碼上加上適當的限制並進行驗證。如果命令對象通過驗證,請對密碼進行編碼並將其添加到要插入/更新的gorm對象。

這樣,gorm對象只能看到編碼密碼,在這裏你應該驗證它不是空的(或者看起來像是一個十六進制編碼的密碼)。

+0

是的,我認爲你是對的,即使我在插入過程中以某種方式入侵它,它在更新中失敗。 痛苦的分類,在多個地方做這個。 – firefly

2

您可以使用事件:

beforeInsert - Executed before an object is initially persisted to the database 
beforeUpdate - Executed before an object is updated 

http://grails.org/doc/latest/guide/GORM.html

你可以看看由彈簧安全插件生成查看示例用戶類。也許這個插件符合你的要求,以至於你不必重新實現這個功能呢?

+1

尼古拉斯感謝您的迴應,但beforeInsert和beforeUpdate被beforeValidate方法調用之前,所以我不能做任何更改。 我需要類似afterValidate事件。 – firefly

+0

我無法在文檔中找到它,但我在BeforeInsert上看到的所有其他信息都表示它在驗證後被調用。你試過了嗎? – Gregg

+0

是的Gregg我做了,我看到beforeValidate之前執行beforeInsert – firefly

0

這項工作:

class User { 

    transient saltSource 
    transient springSecurityService 
    String password 

    static constraints = { 
    password blank: false 
    } 
    static mapping = { 
    password column: '`password`' 
    } 
    def beforeInsert() { 
    encodePassword() 
    } 
    def beforeUpdate() { 
    if (isDirty('password')) { 
     encodePassword() 
    } 
    } 
    protected void encodePassword() { 
    if (springSecurityService) 
     password = springSecurityService.encodePassword(password,saltSource.systemWideSalt) 
    } 

} 

事情要考慮的是如何驗證密碼的複雜性,它應該在這是在控制器和域類之間的中間服務發生還是應自定義密碼字段驗證。

+0

我嘗試了自定義字段驗證器,它不起作用 - 驗證器被調用兩次,當您調用user.save時,再次使用編碼密碼失敗falidation和save()失敗後更新(無錯誤) –

+0

@JohnLittle在我的代碼片段中,您可能會看到我在'beforeUpdate'鉤子中檢查'password'是否'髒',這樣可以避免編碼密碼。並且不確定'無聲地失敗'意味着什麼,你是否期望異常或錯誤信息,而沒有看到你的代碼很難理解,但感覺像自定義驗證問題。 –

相關問題