【问题标题】:Grails Domain modification on save保存时修改 Grails 域
【发布时间】:2011-05-09 16:39:27
【问题描述】:

假设我有一个包含字段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 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
    }
}

现在这在创建新用户时可以正常工作。但是,如果我创建一个用户,给他们一个密码,然后保存他们,然后更改密码并重新保存,这些方法都不会被调用,并且纯测试密码会被存储。

【问题讨论】:

标签: security validation grails passwords grails-domain-class


【解决方案1】:

使用GORM Events

在保存或更新事件中,您可以创建哈希

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

【讨论】:

  • 完美!非常感谢。
  • 想通了,我必须在save() 调用中添加一个flush:true
猜你喜欢
  • 2011-12-06
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 2020-01-01
相关资源
最近更新 更多