Tag Archives: Permissions

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

Creating SharePoint groups programmatically in feature event receiver

The following snippet shows an example of how to add SharePoint groups to a site and set their permission levels. The code is run by adding it to an event receiver for a feature, inside the overridden FeatureActivated method.

 

 public class MBL_PermissionsEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties.Feature.Parent is SPWeb)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(((SPWeb)properties.Feature.Parent).Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            if (!web.HasUniqueRoleAssignments)
                            {
                                web.BreakRoleInheritance(false);
                            }

                            web.Update();

                            SPUserCollection users = web.AllUsers;
                            SPUser member = users[web.Site.RootWeb.SiteAdministrators[0].LoginName];
                            SPMember owner = web.SiteGroups["Owner of " + web.Title];
                            SPRoleAssignment roleAss = null;
                            SPGroup group = null;
                            SPRoleDefinitionCollection roles = web.RoleDefinitions;
                            SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;
                            SPRoleDefinitionBindingCollection roleDefBindings = null;

                            web.SiteGroups.Add("AdminGroup", owner, member, "");

                            web.Update();

                            SPMember ownerSubGroups = web.SiteGroups["AdminGroup"];
                            
                            web.SiteGroups.Add("group1", ownerSubGroups, member, "");
                            web.SiteGroups.Add("group2", ownerSubGroups, member, "");
                            web.Update();

                            group = web.SiteGroups["Owner of " + web.Title];
                            roleAss = new SPRoleAssignment(group);
                            roleDefBindings = roleAss.RoleDefinitionBindings;
                            roleDefBindings.Add(roles["Full Control"]);
                            roleAssignments.Add(roleAss);

                            web.Update();

                            group = web.SiteGroups["AdminGroup"];
                            roleAss = new SPRoleAssignment(group);
                            roleDefBindings = roleAss.RoleDefinitionBindings;
                            roleDefBindings.Add(roles["Full Control"]);
                            roleAssignments.Add(roleAss);

                            web.Update();

                            group = web.SiteGroups["group1"];
                            roleAss = new SPRoleAssignment(group);
                            roleDefBindings = roleAss.RoleDefinitionBindings;
                            roleDefBindings.Add(roles["Contribute"]);
                            roleAssignments.Add(roleAss);

                            web.Update();

                            group = web.SiteGroups["group2"];
                            roleAss = new SPRoleAssignment(group);
                            roleDefBindings = roleAss.RoleDefinitionBindings;
                            roleDefBindings.Add(roles["Read"]);
                            roleAssignments.Add(roleAss);

                            web.Update();
                        }
                    }
                });
            }
        }
    }