Search code examples
grailsgroovy

How to limit domain results with criteria


I am new to grails and I have a question about limiting a query result: domain User:

class User {    
    String login
    String password
    String fname
    String lname
    String role = "user"    

    static constraints = {
        login    (size:5..15, blank:false, unique:true, matches:"[a-zA-Z0-9]+")
        password (size:5..15, blank:false)
        fname    (blank:false)
        lname    (blank:false)
        role     (inList:["user", "admin"])
    }

    String toString(){
        fname & " " & lname
    }

    static mapping = {
        cache true

        columns {
            fname     type:'text'
            lname     type: 'text'
            password  type:'text'
            login     type:'text'
        }   
    }
}

my GSP page snippet that displays the results:

<g:each in="${userInstanceList}" status="i" var="userInstance">
  <tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
    <td><g:link action="show" id="${userInstance.id}">
      ${fieldValue(bean: userInstance, field:   "id")}</g:link></td>
    <td>${fieldValue(bean: userInstance, field: "login")}</td>
    <td>****</td>
    <td>${fieldValue(bean: userInstance, field: "fname")}</td>
    <td>${fieldValue(bean: userInstance, field: "lname")}</td>
    <td>${fieldValue(bean: userInstance, field: "role")}</td>
  </tr>
</g:each>

I call the controller with this code, in separate gsp view:

<g:link class="users" controller="user" params="[sort:'fname',order:'desc']" action="">Manager Users</g:link>

My question is, how do I call the domain and display the results according to the following criteria: first, if the Role is admin, display everything. If the role is not admin, only display the results of certain login value (ie, just show the results where the login = the current user)

Thanks for your help! jason


Solution

  • Define your users controller index action such as:

    def index = {
        if (isAdmin()) {
            [ userInstanceList: User.list(params) ]
        } else {
            [ userInstanceList: User.findAllByLogin(currentUser.login) ]
        }
    }
    

    Of course you need to define isAdmin() and currentUser, but those depend on your security implementation. If using spring-security-core plugin, you can use:

    import org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils
    
    class UsersController {
    
        def springSecurityService
    
        def index = {
            if (SpringSecurityUtils.ifAllGranted(['ROLE_ADMIN'])) {
                [ userInstanceList: User.list(params) ]
            } else {
                [ userInstanceList: User.findAllByLogin(springSecurityService.currentUser.login) ]
            }
        }
    
        // ...
    
    }
    

    See the section on helper classes in the spring-security-core plugin documentation for more info.