Field level security in SharePoint 2010

If you read one of my last posts on creating a rendering template in SharePoint you already know that you can easily create a custom form template for your lists and determine how your fields are rendered.

In this post I will show a quick technique on how you can use a rendering template and place your own security-aware control that will either render or not render depending on the context.

Assuming you already have your custom rendering template defined used in your list, here is how we define two CompositeFields on our form along with other controls:

<tr>
<mycontrols:SecurityAwareCompositeField ID=”Flagged” RequiredGroup=”Moderators” runat=’server’ FieldName=’Flagged’ />
<mycontrols:SecurityAwareCompositeField ID=”FlaggedNotes” RequiredGroup=”Moderators” runat=’server’ FieldName=’FlaggedNotes’ />
</tr>

In here we have Flagged and FlaggedNotes fields which are CompositeFields meaning that they will take a form of any SharePoint control depending on how that control is represented in the list and determined by FieldName. Obviously, we’re using extended version of CompositeField so let’s take a look what the class does:

    public class SecurityAwareCompositeField : CompositeField
    {
        public string RequiredGroup
        { get; set; }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            if (Security.isModerator(SPContext.Current.Web, RequiredGroup))
            {
                base.Visible = true;
            }
            else
            { base.Visible = false; }
        }

    }

In here we have RequiredGroup that will accept the SharePoint Group name that will this field will render for in and simple logic checking whether the user is a “Moderator”. In your case you may want to check for various other roles so let’s take a look at what isModerator is all about:

public static bool isModerator(SPWeb web, string demandGroup)
        {
            foreach (SPGroup group in web.Groups)
            {
                if (group.ContainsCurrentUser && (group.Name.Equals(demandGroup))
                    )
                {
                    return true;
                }
            }
            return false;
        } 

In here we just iterate trough all of the available groups on the web (very handy) and check whether current user is in the group that we care about.

That’s it – very simple logic that cause our control to show or hide depending on the current user beloging to an appropriate group.

This entry was posted in sharepoint, sharepoint 2010 and tagged , , , , . Bookmark the permalink.

Comments are closed.