Zac Mullett Engineering Services
Weblog

Determining web part user permissions on a Web Part Page

A web part I’m creating must display an option to save settings, but only for designer (or administrator) users.

Web Part Page documents are SPListItem objects internally, even though SharePoint makes a distinction between document and list libraries in the user interface. I couldn’t find a path through the object model of finding this SPListItem that my web part instance was a part of. Instead I accessed the item via the current URL and a reference to the context’s SPWeb.

A typical problem with assessing permissions (or roles) for a non-administrative user is that SharePoint savagely denies access to it. Try/catch blocks can be ineffective here, with ASP.NET deciding to redirect to the ‘Access denied’ page. Depending on what you need to do, there are methods involving simple impersonation or more convoluted techniques.

Thankfully I found a peace-loving property .AllRolesForCurrentUser that accurately returns the item-level roles for the current user, regardless of their permissions level.

The resulting function,

    bool IsDesigner()
    {
        SPWeb spWeb = SPControl.GetContextWeb(this.Context);
        string pageUrl = this.Page.Request.Url.AbsolutePath;
        SPListItem spListItem = spWeb.GetListItem(pageUrl);

        foreach (SPRoleDefinition roleDefinition in spListItem.AllRolesForCurrentUser)
        {
            if (roleDefinition.Type == SPRoleType.WebDesigner
                || roleDefinition.Type == SPRoleType.Administrator)
            {
                return true;
            }
        }

        return false;
    }

Tags: ,

Leave a Reply