Code to check to see if a user was a member of a role and it was working properly until that user was placed in a group that had that role instead of the using having the role.
The problem was caused by the GetAssignmentByPrincipal method only returning the assignments to the actual user and not any of the groups that the user was in.
The property AllRolesForCurrentUser in the web returns roles that are assigned to a group that the user is part of as well, but this will only work if you are logged in as that user. To get around this I made a quick method that takes in a SPUser and a role name for a role that is on the root web:
public bool DoesUserHaveRole(SPUser user, string strRole)
{
bool retValue = false;
if (user != null)
{
// Open the site as the current user
using (SPSite site = new SPSite(SPContext.Current.Site.Url, user.UserToken))
{
// Get the root web
using (SPWeb rootWeb = site.RootWeb)
{
SPRoleDefinition role = null;
// Try to get the role by it's name,
// since we can't simply check against null
try
{
role = rootWeb.RoleDefinitions[strRole];
}
catch { }
if (role != null)
{
// Check to see if the user has that role
retValue = rootWeb.AllRolesForCurrentUser.Contains(role);
}
}
}
}
return retValue;
}
Source : http://www.thesug.org/blogs/MOSSMania/Lists/Posts/Post.aspx?List=3f7d7b8a%2Da822%2D409c%2D97ed%2Dd4367160f6d7&ID=34