Search code examples
javascriptsharepointsharepoint-2010csom

clientcontext.executequeryasync gives access denied error in SharePoint 2010


I am having a requirement in which I need to check if user is a member or not of any specific SharePoint group. For this I'm using below code:

function IsCurrentUserMemberOfGroup(groupName, OnComplete) {
   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) {
       // Success function callback  
       OnComplete(userInGroup);
   }

   function OnFailure(sender, args) {
      OnComplete(false);
   }    
}

If current user is site collection administrator then this code is working fine but if user is not site collection administrator then this is not working and giving me below error:

access denied. you do not have permission to perform this action or access this resource

This error occurs at currentContext.executeQueryAsync(OnSuccess,OnFailure);

Can any one help me what I am doing wrong and why I am getting this error? Is there any workaround for this?

Thanks in advance!


Solution

  • This code was not working for me and I was not sure that what was wrong in this code or on the environment. So I just replaced this with below code and I was able to meet my requirement:

    Code

    var IsCurrentUserMemberOfGroup = function (groupName, OnComplete) {
       var userInGroup = false;
       $().SPServices({
           operation: "GetGroupCollectionFromUser",
           userLoginName: $().SPServices.SPGetCurrentUser(),
           async: false,
           completefunc: function (xData, Status) {
                if ($(xData.responseXML).find("Group[Name='" + groupName + "']").length == 1) {
                    userInGroup = true;
                }
            }
        });
        OnComplete(userInGroup);
    }
    

    So basically here I am using SPServices and replaced the code with SPServices code.