Thursday, May 5, 2011

Find the Role/Permissions of a currently logged in user in SharePoint 2010

This method below, tries to Find Role/Permission for the currently logged-in user using SPRoleAssignment and SPRoleDefinition objects. Check it out to learn more about the object model for identifying roles using the SPRoleType enumerator

public void FindRolesForCurrentlyLoggedInUser(SPWeb web, SPUser user)
{
bool IsApprover = false;
bool IsReader = false;
bool IsDirectPermission = false;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
//Check all Groups in the Current Web
foreach (SPGroup group in web.Groups)
{
try
{
//Check If Currently Logged In User has permissions in the all Web Groups
if (group.Users[user.LoginName].ID.ToString().Equals(user.ID.ToString()))
{
//Get Role Assignments
SPRoleAssignment currentUserRole = web.RoleAssignments.GetAssignmentByPrincipal(group as SPPrincipal);

//Go through all Role Definition Bindings
foreach (SPRoleDefinition role in currentUserRole.RoleDefinitionBindings)
{
//Check If Role Type == Reader - Do something
if (role.Type.Equals(SPRoleType.Reader))
{
}
//Administrators access - Full Control - Do something
else if (role.Type.Equals(SPRoleType.Administrator))
{
}
//Contributor access - Contribute - Do something
else if (role.Type.Equals(SPRoleType.Contributor))
{
}
//Web Designer access - Design rights- Do something
else if (role.Type.Equals(SPRoleType.WebDesigner))
{
}
//Limited access - Do something
else if (role.Type.Equals(SPRoleType.Guest))
{
}
//No access on Current Web- Do something
else if (role.Type.Equals(SPRoleType.None))
{
}
}
}

//Get Role Assignments for Current User - If he has been directly assigned permissions
try{SPRoleAssignment directPermission = web.RoleAssignments.GetAssignmentByPrincipal(user as SPPrincipal);}
catch(Exception){/*Best attempt to catch Exceptions*/}
}
catch (Exception)
{
/* Best Attempt to find the User In the Group. Do not throw any exception if a user does not exist in the Group */
}

}
}
}
});
}