0

我有一个包含密码和密码确认字段的域类。这两个分别得到验证。创建这两者相等的验证的最佳实践是什么?

4

2 回答 2

4
class User {

  String password
  String passwordConfirm


  static constraints = {
    password blank: false, nullable: false, minSize: 8, maxSize: 64, validator: {password, obj ->
      def password2 = obj.passwordConfirm
      password2 == password ? true : ['invalid.matchingpasswords']
    }
  }

}

然后将以下内容添加到您的 messages.properties 文件中...

User.password.invalid.matchingpasswords=Passwords do not match

当 user.save() 或 user.validate() 被调用时,这将自动触发。

于 2013-11-14T16:15:31.367 回答
1

我建议你使用 Grails 的安全插件,可能是 Shiro 或 Spring Security Core。

在 Spring Security Core 的文档中有一个更改密码的示例:

def updatePassword = {
   String username = session['SPRING_SECURITY_LAST_USERNAME']
   if (!username) {
      flash.message = 'Sorry, an error has occurred'
      redirect controller: 'login', action: 'auth'
      return
   }
   String password = params.password
   String newPassword = params.password_new
   String newPassword2 = params.password_new_2
   if (!password || !newPassword || !newPassword2 || newPassword != newPassword2) {
      flash.message = 'Please enter your current password and a valid new password'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   User user = User.findByUsername(username)
   if (!passwordEncoder.isPasswordValid(user.password, password, null /*salt*/)) {
      flash.message = 'Current password is incorrect'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   if (passwordEncoder.isPasswordValid(user.password, newPassword, null /*salt*/)) {
      flash.message = 'Please choose a different password from your current one'
      render view: 'passwordExpired', model: [username: session['SPRING_SECURITY_LAST_USERNAME']]
      return
   }

   user.password = newPassword
   user.passwordExpired = false
   user.save() // if you have password constraints check them here

   redirect controller: 'login', action: 'auth'
}
于 2013-11-14T16:16:33.940 回答