Wednesday, June 20, 2012

Securing SharePoint lists by code

Rather than stuffing configuration keys into *.CONFIG files, it's more convenient to use SharePoint lists instead. This makes it easier to alter configuration settings, as for each change we would need to deploy a new .CONFIG file and involve SysAdmins, get approval from the management, et cetera.

But obviously, you do not want all users to have access to these, if you will, configuration lists. Manually setting all permissions per list and user group would be a nag. Therefore, I'm doing this by code, using the feature event receiver. I basically fetch the SPLists required, break the inheritance and re-set the permissions. The 'userGroup' variable holds the name of the user group associated with the feature. Same goes for the 'prefixList' variable.



public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            const string userGroup = "TeamGary";
            const string prefixList = "config.";

            using (SPSite site = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb web = site.OpenWeb())
                {
                    List<string> fdtListTitles = new List<string>();

                    // get all feature-related SPList titles
                    foreach (SPList list in web.Lists)
                    {
                        if (list.Title.Substring(0, 7) == prefixList)
                        {
                            web.AllowUnsafeUpdates = true;

                            // break inheritance from parent
                            list.BreakRoleInheritance(false);

                            // remove all permissions from list, except for userGroup
                            SPGroupCollection groupCollection = list.ParentWeb.SiteGroups;
                            SPGroup group = groupCollection[userGroup];
                            SPRoleDefinitionCollection roleDefCollection = list.ParentWeb.RoleDefinitions;
                            SPRoleDefinition roleDefinition = roleDefCollection["Read"]; // set access level here
                            SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)group);

                            roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

                            list.RoleAssignments.Add(roleAssignment);

                            list.Update();
                        }
                    }
                }
            }
        }

No comments:

Post a Comment