9

is there some pretty way to check if some specific user (not the one that is logged in) has some specific role?

Here is grails example (generally the same for plain Java but syntax):

def user = User.get(1) //Get user with id 1
if (ifAnyGranted(user,"ROLE_ADMIN")) { //This is the line I need to implement somehow
...
}

Thanks in advance.

bezmax
  • 25,562
  • 10
  • 53
  • 84
  • 2
    it's a bit unclear what you are asking. you are looking for something "prettier" than above code? Does the snippet you provide work for you? – Jean Barmash Dec 02 '09 at 18:43
  • That line was an example to show precisely what I need. There is no function ifAnyGranted(user,roles). – bezmax Dec 03 '09 at 13:55

4 Answers4

9

I assume, your User domain class holds a hasMany refernece to your Role class like this:

class User  {
    static hasMany = [authorities: Role]
    //....
}
class Role  {
    static belongsTo = User
    String description
    String authority
    //....
}

So your code for role-checking is simple:

User user = User.get(1)
if (user.authorities.any { it.authority == "ROLE_ADMIN" }) {
    // user is a admin
}

An updated answer can be found here.

Community
  • 1
  • 1
Stefan Armbruster
  • 39,465
  • 6
  • 87
  • 97
  • 1
    To use this technique to check the current logged in user: def authenticateService def pricipalInfo = authenticateService.principal() def user = User.findByUsername(pricipalInfo.username) if (user.authorities.any { it.authority == "ROLE_ADMIN" }) { // user is a admin } – Brad Rhoads Dec 16 '09 at 00:08
4
if (grails.plugin.springsecurity.SpringSecurityUtils.ifAllGranted("ROLE_ADMIN"))
{
   ...
}
Pablo Pazos
  • 3,080
  • 29
  • 42
3

If you're using the Spring Security Plugin and want to check the current logged in user:

import org.codehaus.groovy.grails.plugins.springsecurity.AuthorizeTools

. . .

if (AuthorizeTools.ifAllGranted("ROLE_ADMIN")){
               //user is an admin
}
Brad Rhoads
  • 1,828
  • 3
  • 29
  • 52
  • Just noticed the question was specifically not about the logged in user. Hope this is useful anyway. – Brad Rhoads Dec 16 '09 at 00:16
  • 1
    I realize this is an old answer, but it appears that AuthorizeTools has been replaced by SpringSecurityTools – David May 04 '16 at 00:33
0

I case you want to check the current logged in user, you don't need to query User domain, since you've already injected springSecurityService, so you could've just write:

def springSecurityService

def someAction(){
    if (principal.authorities.any { it.authority == 'ROLE_ADMIN'}){
        //...
    } else {
        //...
    }
}
Ibrahim.H
  • 1,062
  • 1
  • 13
  • 22