Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if specific user has a role

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.

like image 517
bezmax Avatar asked Dec 02 '09 15:12

bezmax


3 Answers

if (grails.plugin.springsecurity.SpringSecurityUtils.ifAllGranted("ROLE_ADMIN"))
{
   ...
}
like image 144
Pablo Pazos Avatar answered Sep 24 '22 05:09

Pablo Pazos


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.

like image 21
Stefan Armbruster Avatar answered Sep 26 '22 05:09

Stefan Armbruster


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
}
like image 41
Brad Rhoads Avatar answered Sep 22 '22 05:09

Brad Rhoads