Check if Current Users belongs to SP group using javascript Client Side Object Model
Asked Answered
E

3

12

I havent found a specific example of how to get the current user and then check if it belongs to a specific sharepoint group, as I havent found anything I cant provide a code,

help on the right direction is appreciated.

Eberto answered 2/3, 2014 at 0:6 Comment(0)
M
19

SharePoint 2013 CSOM

Prerequisites: compatible with SharePoint 2013 CSOM API only since SP.GroupCollection.getByName Method is not available in SharePoint 2010

How to check if current user belongs to SharePoint group via CSOM (JavaScript):

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);

        var group = allGroups.getByName(groupName);
        currentContext.load(group);

        var groupUsers = group.get_users();
        currentContext.load(groupUsers);

        currentContext.executeQueryAsync(OnSuccess,OnFailure);

        function OnSuccess(sender, args) {
            var userInGroup = false;
            var groupUserEnumerator = groupUsers.getEnumerator();
            while (groupUserEnumerator.moveNext()) {
                var groupUser = groupUserEnumerator.get_current();
                if (groupUser.get_id() == currentUser.get_id()) {
                    userInGroup = true;
                    break;
                }
            }  
            OnComplete(userInGroup);
        }

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

Usage

IsCurrentUserMemberOfGroup("Approvers", function (isCurrentUserInGroup) {
   if(isCurrentUserInGroup)
   {
      //...
   }
});

SharePoint 2010/2013 CSOM

function isUserMemberOfGroup(userId, groupId, success,error) {

     var ctx = SP.ClientContext.get_current(); 
     var allGroups = ctx.get_web().get_siteGroups();
     var group = allGroups.getById(groupId);
     ctx.load(group,'Users');

     ctx.executeQueryAsync(
        function(sender, args) {
            var userInGroup = findUserById(group.get_users(),userId);
            success(userInGroup);
       },
       error);    

       var findUserById = function(users,id){
           var found = false;
           var e =  group.get_users().getEnumerator();
           while (e.moveNext()) {
                var user = e.get_current();
                if (user.get_id() == id) {
                    found = true;
                    break;
                }
           } 
           return found; 
       };
}

Usage

var currentUserId = _spPageContextInfo.userId;
var groupId = 4;
isUserMemberOfGroup(currentUserId, groupId, 
      function (isCurrentUserInGroup) {
          if(isCurrentUserInGroup)
              console.log('Current user is a member of Owners group'); 
          else
              console.log('Current user is not a member of Owners group'); 
      },
      function(sender,args){
         console.log(args.get_message());
      });
Miserly answered 2/3, 2014 at 11:1 Comment(4)
This will only work, if the user is a direct member of the SharePoint group, right? What if the user is member of an AD group, that is member of the SP group? Is this possible via JavaScript?Weber
That's right. Unfortunately it does not seem possible to determine whether user is a member of AD group using this approachMiserly
The first approach with only one executequery is not working for SP2013 , "The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.". Can you elaborate on the first approach as it seems not to be working for me. Anything specific to be done for that?Pechora
I get access denied when trying to load groups with Users. Does the user need to be have an impersonation step (which is not available) to check the users in the group? Since this is JSCOM, I can't do impersonation and might end up having to write it in server side code.Northwestward
E
6

Here's a quicker way with SharePoint 2013:

function CheckCurrentUserMembership() {

    var clientContext = new SP.ClientContext.get_current();
    this.currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(this.currentUser);

    this.userGroups = this.currentUser.get_groups();
    clientContext.load(this.userGroups);
    clientContext.executeQueryAsync(OnQuerySucceeded);
}

function OnQuerySucceeded() {
         var isMember = false;
         var groupsEnumerator = this.userGroups.getEnumerator();
          while (groupsEnumerator.moveNext()) {
             var group= groupsEnumerator.get_current();               
             if(group.get_title() == "Administrator Group") {
                 isMember = true;
                 break;
             }
          }

          OnResult(isMember);
}

function OnQueryFailed() {
          OnResult(false);
}
Enzymology answered 11/2, 2015 at 23:54 Comment(3)
With this I get the error 'Cannot read property 'getEnumerator' of undefined' on this.userGroups.getEnumerator();Carlos
In SharePoint Foundation 2013, I am getting the same error, Did anyone figure out the solutions?Reluctant
IN SP2013 Enterprice "Cannot read property 'getEnumerator' of undefined"Sedgewinn
V
2

If anyone is interested. This approach can be used when you want to check if a user is a member of a group using the group name.

    var currentUserIsMemberOf = function(groupName){
      var found = false;
      var dfd = $.Deferred(function(){
         SP.SOD.executeOrDelayUntilScriptLoaded(function(){
            context = new SP.ClientContext.get_current();
            allGroups = context.get_web().get_siteGroups();
            context.load(allGroups);
            context.load(allGroups, 'Include(Users)');

            context.executeQueryAsync(
               function(){
                  var groupsEnumerator = allGroups.getEnumerator();
                  while (groupsEnumerator.moveNext()) {
                      var group = groupsEnumerator.get_current();               
                      if(group.get_title() == groupName) {
                          var usersEnumerator = group.get_users().getEnumerator();
                          while (usersEnumerator.moveNext()) {
                             var user = usersEnumerator.get_current();   
                             if(user.get_id() == _spPageContextInfo.userId) {
                                found = true;
                                break;
                             }
                          }
                      }
                   }
                  dfd.resolve(found);
               },
               function(){
                  dfd.reject(args.get_message());
               }
            );
         }, 'sp.js');
      });
      return dfd.promise();
   }

You can use like this

currentUserIsMemberOf("Members of Demo").done(function(result){ 
                                                  alert(result) 
                                                });

Note this code use Promise, you can reference jQuery use your own custom Deferred object or remove Deferred object.

Velum answered 19/3, 2016 at 0:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.