Wednesday, November 19, 2008

Checking if logged in user is member of Sharepoint Site

To check if current logged in user is member of current site. We could loop through groups available for the current site and check if user is member of the group.

SPWeb object defines a method SPWeb.IsCurrentUserMemberOfGroup(int groupid). This method takes the credentials of logged in user and Group ID as parameter.
Group id can be obtained from SPGroup object. SPWeb object also has one property SPWeb.Groups. Simply loop through this collection and check if logged in user is member of this group.

Following code snippet checks if user is member of group (except visitor group).

SPWeb web = SPContext.Current.Web;
bool isMember = false;
foreach (SPGroup group in web.Groups)
{
//If it is visitors group, do not check user membership
if(group != web.AssociatedVisitorGroup)
isMember = web.IsCurrentUserMemberOfGroup(group.ID);
//Check if user is member of this site.
if (isMember==true)
break;
}
if (isMember)
{
// other task to do if user is member
}

Note:
SPWeb class has properties that can be used to determine Visitors Groups/Members Groups and Groups associated with web site.

AssociatedGroups
Gets a list of the groups that are associated with the Web site.
AssociatedMemberGroup
Gets the users who have been given contribute permissions to the Web site.
AssociatedOwnerGroup
Gets or sets the associated owner groups of the Web site.
AssociatedVisitorGroup
Gets or sets the associated visitor group of the Web site.

Happy MOSS...ing!!!
Sudhir Kesharwani