Sharepoint - Sharepoint 2013 - show ribbon to admin only

How about Security Trimming that Ribbon in the masterpage?

<!--CS: Start Security Trim Snippet-->
    <!--SPM:<%@Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>-->
    <!--MS:<SharePoint:SPSecurityTrimmedControl runat="server" AuthenticationRestrictions="AuthenticatedUsersOnly" Permissions="AddAndCustomizePages" PermissionContext="RootSite">-->
        <!--PS: Start of READ-ONLY PREVIEW (do not modify)--><span><!--PE: End of READ-ONLY PREVIEW-->
            <div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle">
            ...
            </div>
        <!--PS: Start of READ-ONLY PREVIEW (do not modify)--></span><!--PE: End of READ-ONLY PREVIEW-->
    <!--ME:</SharePoint:SPSecurityTrimmedControl>-->
    <!--CE: End Security Trim Snippet-->

MSDN Reference:

https://msdn.microsoft.com/en-us/library/office/jj822366.aspx


CSS + JS Solution

Add following CSS in your master page

#RibbonContainer{
  display: none;
}

Now GET current users details

/_api/web/currentuser?$expand=Groups

Make a GET request to the above end-point, it will return current user's details with his/her Groups

Now check if current user IsSiteAdmin, then display Ribbon again.

if (response.d.IsSiteAdmin){
   document.querySelector("#RibbonContainer").style.display = 'block';
}

If you need to check if current user exists in particular Group, then

var groupName = "Your Group Name";

var isUserExistsInGroup = response.d.Groups.results.some(function(g) {
    return g.Title == groupName;
});

if (isUserExistsInGroup) {
    document.querySelector("#RibbonContainer").style.display = 'block';
}

Full JS Code put it in your master page

(function() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("GET", _spPageContextInfo.webAbsoluteUrl + '/_api/web/currentuser?$expand=Groups');

    xmlhttp.setRequestHeader("Accept", "application/json;odata=verbose");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                var response = xmlhttp.responseText;

                if (response.d.IsSiteAdmin) {
                    document.querySelector("#RibbonContainer").style.display = 'block';
                }

                var groupName = "Your Group Name"; //Give here your Group Name

                var isUserExistsInGroup = response.d.Groups.results.some(function(g) {
                    return g.Title == groupName;
                });

                if (isUserExistsInGroup) {
                    document.querySelector("#RibbonContainer").style.display = 'block';
                }

            } else {
                alert('Error: ' + xmlhttp.statusText)
            }
        }
    }

    xmlhttp.send();

})();

Tags:

Javascript