Please note: This blog is no longer active. My new blog is located at http://blog.timwheeler.io

Wednesday, December 10, 2014

Create Security Groups and Assign Permissions in SharePoint 2013

Here is a fun little helper for creating security groups with a permission assignment.
I use the word fun because I have been working with SharePoint too long and my brain now works in reverse.


/// <summary>
    /// Security Helper
    /// </summary>
    public class SecurityHelper
    {
        public static bool GroupExists(SPGroupCollection groups, string name)
        {
         
            if (String.IsNullOrEmpty(name) || (name.Length > 255) ||(groups == null) || (groups.Count == 0))
            {
                return false;
            }
            return groups.Cast<SPGroup>().FirstOrDefault(t => t.Name == name) != null;
        }
        /// <summary>
        /// Creates a group if it does not exist.  It will also assign a permission level to the group.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="groupName"></param>
        /// <param name="permissionLevel"></param>
        /// <param name="description"></param>
        /// <param name="owner"></param>
        /// <returns>The Group</returns>
        public static SPMember CreateGroup(SPWeb web, string groupName, string permissionLevel, string description, SPMember owner = null)
        {
            string uniqueGroupName = String.Format("{0} - {1}", web.Name, groupName);
            if (!GroupExists(web.SiteGroups, uniqueGroupName))
            {
                var role = web.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(t => t.Name == permissionLevel);
                if (role == null)
                {
                    throw new KeyNotFoundException(String.Format("The Security Permission level {0} does not exist at web {1}.", permissionLevel, web.Url));
                }
                if (owner == null)
                {
                    owner = web.CurrentUser;
                }
                web.SiteGroups.Add(uniqueGroupName, owner, null, description);
                SPGroup group = web.SiteGroups.GetByName(uniqueGroupName);
                var assignment = new SPRoleAssignment(@group);
                assignment.RoleDefinitionBindings.Add(role);
                web.RoleAssignments.Add(assignment);
            }
            return web.SiteGroups.GetByName(uniqueGroupName);
        }
    }

No comments:

Post a Comment