Sunday, March 8, 2009

How to find a user (SPUser or domain user) belongs to a AD (active Directory) group / domain group from sharepoint

First, Lets think a set of domain users belong to a Active Directory/ domain group named $DotNet-Developers. Of course, you have added users from active directory, not from sharepoint. Now, you want to find out from sharepoint whether a user belongs to that group. To do this, what you need to do is:

1. create a sharepoint group (SPGroup) in the site, for example named DotNetSPGroup.
2. Add the Domain group ($DotNet-Developers) inside that sharepoint Group.
3. Give that SPGroup at least "read permission" in the site.
4. Search for user under that SPGroup using group.ContainsCurrentUser method.

Now, while running any specific program, you want to find out whether a specific user belongs to that active directory group or not. Lets think, you are getting the user from a "Person or group field" from sharepoint. Now retrieve the SPUser from that field. after that just use this method:


private bool IsUserInGroup(SPUser targetUser, SPItemEventProperties properties, string groupName)
{
bool containsUser=false;


using(SPSite targerSite= new SPSite(properties.SiteId,targetUser.UserToken))
{
SPWeb targetWeb=targerSite.OpenWeb(properties.RelativeWebUrl);

SPGroupCollection LMSGroups = properties.OpenWeb().Groups;
try
{
SPGroup groupForDotNetDev = LMSGroups[groupName];
if (groupForDotNetDev.ContainsCurrentUser)
{
containsUser=true;
}
}
catch (Exception e)
{
}
}
return containsUser;
}

This should do the trick.

using(SPSite targerSite= new SPSite(properties.SiteId,targetUser.UserToken)) changes the current user to that user. Then, you can use groupName.ContainsCurrentUser user method to check whether the user is inside that group or not. This method even searches inside AD groups, if that AD group is added inside an SPGroup. So, it works just fine.

I must thank El Blanco for his post.

No comments: