Valid for Sitecore
5.3
Our code needs to list all Users which belong to a specific Role
Sitecore versions: tested with 5.3.0.
The Problem:
Our code needs to list all Users which belong to a specific Role.
1.
The Solution
Use the Sitecore.SecurityModel.UserItem.IsInRole() method to check a given User.
// select a Role and list all Users of the Role
private void GetUsersByRole(Sitecore.SecurityModel.RoleItem role)
{
// retrieve the appropriate security database
Database dbSecurity = Sitecore.Configuration.Factory.GetDatabase("security");
Sitecore.SecurityModel.UserItem[] users = this.GetUsers(dbSecurity);
Response.Write("<hr />All users from the " + role.Name + " role: <br />");
foreach(Sitecore.SecurityModel.UserItem ui in users)
{
// check whether the current User is in the given Role
if (ui.IsInRole(role.ID))
{
Response.Write(ui.Name + "<br />");
}
}
}
// list all the Database security Users.
private Sitecore.SecurityModel.UserItem[] GetUsers(Sitecore.Data.Database db)
{
// create a query that will handle the User retrieval
// here we simply rely on the User's Template ID
string query = "//*[@@templateid='" + Sitecore.TemplateIDs.User + "']";
Sitecore.Data.Items.Item[] items = db.SelectItems(query);
Sitecore.SecurityModel.UserItem[] users = new Sitecore.SecurityModel.UserItem[items.Length];
for (int i = 0; i < users.Length; i++)
{
users[i] = new Sitecore.SecurityModel.UserItem(items[i], Sitecore.Context.Domain);
}
return users;
}