Search code examples
grailsgrails-ormcriteriashiro

Proper Criteria for Shiro plugin in Grails


I have Shiro domain classes as below:

class ShiroUser {
String email
String password

static hasMany = [ roles: ShiroRole, permissions: String ]

static constraints = {
    email(nullable: false, blank: false, unique: true)
    }
}


class ShiroRole {
String name

static hasMany = [ users: ShiroUser, permissions: String ]
static belongsTo = ShiroUser

static constraints = {
    name(nullable: false, blank: false, unique: true)
     }
}

I received ShiroUser's email from params.email. And I want to find out the permission that belongsTo ShiroUser using criteria().

I tried the below code, but couldn't succeed.

 def criteria= permissions.createCriteria().listDistinct {
                ShiroRole{
                     ShiroUser{
                         eq("email", params.email)
                        }
                    }
                }

Solution

  • Your criteria is wrongly built. I'd keep it simple and put like:

    def permissions = ShiroUser.findByEmail( params.email )?.roles*.permissions.flatten() as Set
    

    If you want to stick with criteria:

    def permissions = ShiroRole.createCriteria().listDistinct {
                        projections{ 
                           property 'permissions'
                        }
                        users{
                             eq "email", params.email
                        }
                    }