logo

Checking if a user belongs to a user group

You can check if a user belongs to a certain group, for example, Administrators, by using the following scripts.

Script with PublicAPI

Note
Documentation on PublicAPI is available here
Attention
The script below is relevant for ELMA up to 3.12.1 inclusive.

Namespaces:

using EleWise.ELMA.API;

Script text:

PublicAPI.Portal.Security.UserGroup.CheckUserInGroup(PublicAPI.Portal.Security.User.GetCurrentUser(),
PublicAPI.Portal.Security.UserGroup.Find("Name = ’Administrators’").FirstOrDefault())

Script without PublicAPI

Use the following namespaces:

using EleWise.ELMA.Security.Managers;
using EleWise.ELMA.Security.Models;
using EleWise.ELMA.Security.Services;

Script text:

//loading the "Administators" group
var admins = UserGroupManager.Instance.Load("Administrators");
//checking, if the user belongs to this group
var inAdmins = UserGroupManager.Instance.GetUsersByGroup(admins.Id).Any(a => a == AuthenticationService.GetCurrentUser<IUser>().Id);

As a result, the local boolean variable inAdmins is true if the user belongs to the "Administrators" group, and if not, the variable is false.

Instead of AuthenticationService.GetCurrentUser<IUser>() you can specify any other User type variable, for example, a context or a local one.