Search code examples
sharepointsharepoint-list

How to check if a sharepoint group has read or write permission in SPListItem


How to check if a sharepoint group has read or write permission in SPListItem.

We can check SPUser permission using this code:

SPBasePermissions perms = SPBasePermissions.EditListItems;
spListItem.DoesUserHavePermissions(spUser, perms);

But I couldn't find anywhere how should I check permission for a group. This is what I am looking for:

spListItem.DoesUserHavePermissions(spGroup, perms);

Solution

  • When checking permissions for a group, you can look directly at the SPListItem's RoleAssignments property (which is a collection of SPRoleAssignment objects) and see if any role assignment's Member property corresponds to the group you want.

    Unlike users, groups can't be nested within Active Directory groups and SharePoint groups, so you don't need to look any deeper than the direct role assignments.

    The simplest solution is to use the GetAssignmentByPrincipal method of the SPRoleAssignmentCollection object.

    bool hasEdit = false;
    SPRoleAssignment ra = spListItem.RoleAssignments.GetAssignmentByPrincipal(spGroup);
    SPRoleDefinitionBindingCollection permissions = ra.RoleDefinitionBindings;
    foreach(SPRoleDefinition level in permissions)
    {
        if(level.BasePermissions & SPBasePermissions.EditListItems == SPBasePermissions.EditListItems 
          || level.BasePermissions & SPBasePermissions.FullMask == SPBasePermissions.FullMask)
        {
             hasEdit = true;
             break;
        }
    }
    

    Note that in the above code, when comparing the BasePermissions property of a permission level to a specific SPBasePermissions enumeration, I'm using the approach recommended by Microsoft's Guidelines for FlagsAttribute and Enum:

    • A convenient way to test whether a flag is set in a numeric value is to perform a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, then test whether the result of that operation is equal to the flag enumerated constant.