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

后端 未结 3 1574
说谎
说谎 2020-12-14 23:02

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 cod

相关标签:
3条回答
  • 2020-12-14 23:13

    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);
    }
    
    0 讨论(0)
  • 2020-12-14 23:13

    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.

    0 讨论(0)
  • 2020-12-14 23:23

    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());
          });
    
    0 讨论(0)
提交回复
热议问题