Thursday, August 4, 2016

Check If current User member of Sharepoint Group using JSOM (2013 or 2010)

The following block of code will help you identify if the current logged in user is already a part of any SharePoint group .


Say for example, I need to check if the current user belongs to Elninos Football Team SharePoint group .  You can use the following scripts in script web parts, content editor web parts, or visual web parts.


Please see the code below:

<script>
// Provide the Group name
var grpName="Elninos Football Team";
$(document).ready(function() {

 ExecuteOrDelayUntilScriptLoaded(IsCurrentUserMemberOfGroup, "sp.js");
 
});
     
  });
//Ready function ends

function IsCurrentUserMemberOfGroup()
{
       
        var userInGroup;
        var currentContext = new SP.ClientContext.get_current();
        var currentWeb = currentContext.get_web();    
        var currentUser = currentContext.get_web().get_currentUser();
        currentContext.load(currentUser);
        var allGroups = currentWeb.get_siteGroups();
        currentContext.load(allGroups);
        currentContext.load(allGroups, 'Include(Users)');
        currentContext.executeQueryAsync(OnSuccess,OnFailure);
       
  
        function OnSuccess(sender, args) {
            var userInGroup = false;
          
            var groupEnumerator = allGroups.getEnumerator();
            while (groupEnumerator.moveNext() && !userInGroup)
            {
               var oGroup = groupEnumerator.get_current();
               if (oGroup.get_title() ==  grpName )
               {
                  var collUser = oGroup.get_users();
                  var userEnumerator = collUser.getEnumerator();
                  while (userEnumerator.moveNext() && !userInGroup)
        {
                  var oUser = userEnumerator.get_current();
                  if (oUser.get_id() == currentUser.get_id())
                   {
                    userInGroup = true;
                    alert("User is a member of the Group you have given");
                   }
                   }
                }
            }
       }
        function OnFailure(sender, args) {
  alert("User not found");
        }      
}
</script>

No comments:

Post a Comment

Rename a Web Application in Sharepoint : A solution using powershell

Here is a small script that will enable you all to change a SharePoint Web Application name . We can use the following SharePoint Pow...