Tag Archives: Show webPart

Hide/Show WebPart depending on current users affiliation

I was very surprised when I started to search for a solution to the task of only showing a webPart I made for users belonging to certain permission groups and found out that there wasn’t any really simple way of doing this. I thought that this is something people should want to do all the time. I found a couple of blogs suggesting creating an audience and hiding the WebPart for that audience. This would not actually affect security however, and felt like a bad solution. Of course you could break and change the permission for the webPart in the webPart gallery, but still not good enough.

Instead I found an easier way of doing this in the WebPart class itself. I’m not sure this is a good solution or not, and there are possibly tons of faults in it, but it works at least.

Basically I do two things:

  • Check if the current user belongs to the correct groups.
  • Set the WebPart to hidden if user does not belong to the right groups.

This is how I check that the current user belongs to the correct groups (If you want to check the permission levels instead, a bit more code is needed. Check this link for example):

private bool UserHasAccess()
        {
            bool hasAccess = false;
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        foreach (SPGroup userGroup in web.CurrentUser.Groups)
                        {
                            if (userGroup.Name == "Group1" ||
                                userGroup.Name == "Group2" ||
                                userGroup.Name == "Group3" )
                            {
                                hasAccess = true;
                            }
                            else
                            {
                                hasAccess = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return hasAccess;
        }

Then I just show or hide the webPart:

private void ManageVisibility()
        {
            this.Hidden = !UserHasAccess();
        }

Finally, call the method ManageVisibility from the overridden CreateChildControls in your WebPart and voilá! The webPart will be shown for users belonging to the selected groups only. As I said before, this does not check permission levels, only group affiliation.

Advertisements