Check if user is in group by group name

1k views Asked by At

I may be thinking about this wrong, but shouldn't it be a very common thing to need to check if a user belongs to a certain group? For example, if you want to show a certain menu item only to "Administrators", shouldn't there be a way within my view file to easily check if the user belongs to that group?

I see that there is a inGroup() function on the user, but this requires that you first fetch the group object, and pass it into the function, rather than simply passing the group name, for example, $user->inGroup('Administrators');. I also realize I could write my own method to accept the group name, look it up, and then use that in the exiting inGroup() method.

However, the fact that this is not much more obvious in the docs makes me believe I am thinking about it in the wrong way.

Would the preferred way be to give the "Administrators" group an "admin: 1" permission, and therefore just check if the user has that permission rather than checking if they are in the group?

If so, I am struggling to see the value of a group at all since you aren't able to easily use them to determine access; instead, you need to use the individual permissions that the group contains.

1

There are 1 answers

0
omar j On

You can check to see if a user belongs to a group easily:

$user = Sentry::findUserById(1);

$adminGroup = Sentry::findGroupByName('Admin');

$isAdmin = $user->inGroup($adminGroup);

However the best approach is to use permissions. You can setup an 'Admin' group with permissions to 'manage user accounts'. You then simply check to see if the user has permission to 'manage user accounts' as opposed to checking whether they belong to the Admin group. In my 'group' table i have a row like this:

id | name | permissions

1 | Admin | {"manageUserAccounts":1}

I can now check whether a user has permission to 'manageUserAccounts' with the following:

$user = Sentry::findUserById($userId);

if ($user->hasPermission('manageUserAccounts') {
    print 'You can manage user accounts';
}
else {
    print 'Oops, you cant manage user accounts';
}

Note that the 'user' table is connected to the 'group' table via the user_groups table. See the Sentry documentation for more info on how to fine grain permissions. It's quite powerful.