2015-08-17 1 views
0

Я нашел отличное сообщение о том, как узнать, является ли пользователь частью одной группы в SharePoint 2010; SP 2013 улучшился и немного изменился. Вот исходная ссылка: http://styledpoint.com/blog/sharepoint-2010-check-to-see-if-user-exists-in-a-group-via-javascript-ecma/SharePoint 2010 Найдите, находится ли пользователь в одной из перечисленных групп Javascript

Я изменил это, потому что для нашего случая использования требуется определить, является ли пользователь членом одной из нескольких групп, чтобы показать или скрыть раздел html. Проблема в том, что я не могу объединить коллекцию userGroups, которая содержит пользователя, чтобы узнать, является ли пользователь частью более чем одной группы. Если я не объединять пользовательскую коллекцию, функция возвращает true/false для каждой включенной группы. Есть предположения?

//http://styledpoint.com/blog/sharepoint-2010-check-to-see-if-user-exists-in-a-group-via-javascript-ecma/ 
function IsCurrentUserMemberOfAnyListedGroup(strGroupName, functionComplete2) { 
    //Setup Vars 
    currentContext = null; 
    currentWeb = null; 
    allGroups = null; 
    leaderGroup = null; 
    currentUser = null; 
    groupUsers = null; 
    //Get an instance of the Client Content. 
    currentContext = new SP.ClientContext.get_current(); 
    //Grab the client web object. 
    currentWeb = currentContext.get_web(); 
    //Get the current user object 
    currentUser = currentContext.get_web().get_currentUser(); 
    currentContext.load(currentUser); 
    //Setup the groupColletion. 
    allGroups = currentWeb.get_siteGroups(); 
    currentContext.load(allGroups); 
    //currentContext.load(allGroups, 'Include(Title, Id, Users.Include(Title, LoginName))'); 


    //Now populate the objects above. 
    currentContext.executeQueryAsync(Function.createDelegate(this, GetAllGroupsExecuteOnSuccess2),Function.createDelegate(this, ExecuteOnFailure2)); 

    // GroupCollection - Load - SUCCESS 
    function GetAllGroupsExecuteOnSuccess2(sender, args) { 
     // CHECK THE GROUPS 
     // Time to Enumerate through the group collection that was returned. 
     var groupEnumerator = allGroups.getEnumerator(); 
     var groupexists = false; 
     var groupUsers = null; 
     // Loop for the collection. 
     while (groupEnumerator.moveNext()) { 
      //Grab the Group Item. 
      var group = groupEnumerator.get_current(); 

      //Since you are enumerating through out the group names, theoretically you should be able to list multiple groups like editors and admins 
      //Separate the group name into an array so that multiple groups could be used 
      //alert(strGroupName);   

      var myarray = strGroupName.split(','); 

      for(var i = 0; i < myarray.length; i++) 
      { 

       //console.log(myarray[i]); 
       if (group.get_title().indexOf(myarray[i]) > -1) { //if (group.get_title().indexOf(strGroupName) > -1) { 
        //console.log("'"+myarray[i]+"'"); 
        groupexists = true; 
        // Now that we have the group let's grab the list of users. 
        if (groupUsers == null) { 
         groupUsers = group.get_users();   
        } else { 
         //groupUsers = groupUsers.addUser(group.get_users());       
         //groupUsers = groupUsers.concat(group.get_users());       
         //groupUsers = groupUsers.Concat(group.get_users());       
         groupUsers = groupUsers.merge(group.get_users());      
        } 

        //console.log(group.get_users()); 
        break; 
       } 
      } 
      /*if (group.get_title().indexOf(strGroupName) > -1) { 
      // Now that we have the group let's grab the list of users. 
      groupUsers = group.get_users(); 
      currentContext.load(groupUsers); 
      currentContext.executeQueryAsync(Function.createDelegate(this, SingleGroupExecuteOnSuccess),Function.createDelegate(this, ExecuteOnFailure)); 
      }*/ 
     } 
     //console.log(groupexists); 
     if (groupexists == false) { 
      //Run the delegate function and return false because there was no match for the group name. 
      functionComplete2(false); 
     }  
      //After iterating through the provided groups, then call the success function 
      //User could be listed more than once, but you need it to show up only once 
      currentContext.load(groupUsers); 
      currentContext.executeQueryAsync(Function.createDelegate(this, SingleGroupExecuteOnSuccess2),Function.createDelegate(this, ExecuteOnFailure2)); 
    } 

    // Single Group - Load - SUCCESS 
    function SingleGroupExecuteOnSuccess2(sender, args) { 
     alert('SingleGroupExeSuc2'); 
     // Time to setup the Enumerator 
     var groupUserEnumerator = groupUsers.getEnumerator(); 
     // This is the flag to set to true if the user is in the group. 
     var boolUserInGroup = false; 
     // and start looping. 
     while (groupUserEnumerator.moveNext()) { 
      //Grab the User Item. 
      var groupUser = groupUserEnumerator.get_current(); 
      // and finally. If a Group User ID Matches the current user ID then they are in the group! 
      if (groupUser.get_id() == currentUser.get_id()) { 
       console.log(groupUser.get_id()); 
       boolUserInGroup = true; 
       break; 
      } 
     } 
     //Run the delegate function with the bool; 
     functionComplete2(boolUserInGroup); 
    } 

    // GroupCollection or Single Group - Load - FAILURE 
    function ExecuteOnFailure2(sender, args) { 
     //Run the delegate function and return false because there was no match. 
     alert('failed'); 
     functionComplete2(false); 
    } 
} 

Вот как я звоню функции:

IsCurrentUserMemberOfAnyListedGroup("Admin,Member", function (isCurrentUserInGroup) {  
        if(isCurrentUserInGroup) { 
         alert('Show');  // The current user is in the group! Hurrah!  
        } else { 
         alert('Dont Show'); 
        } 
       }); 

ответ

0


Я думаю, что вы сделали это слишком complecated ..
почему вы не просто получить все группы пользователей (например, с помощью это решение: http://spservices.codeplex.com/wikipage?title=GetGroupCollectionFromUser&referringTitle=Users%20and%20Groups) в качестве строки и для каждого имени урожая, которое вы должны искать, просто получите индекс в строке ... если он равен -1, по крайней мере, один раз - возвращает false и break ..

Надеюсь, что это поможет,
Andrey.
(можно вставить пример кода позже, при необходимости .. не имеют доступа прямо сейчас)

+0

В настоящее время я использую только одну группу. Когда мне нужно сложнее, я использую SPServices. Я надеюсь, что кто-то может сделать предложение, что я могу опубликовать полный ответ для других, чтобы найти. – H2O

0

это то, что я имел в виду: (проверено, как работает, проверено, является ли пользователь в нескольких группах. вы можете поместить все группы для проверки в массив и проверить их в цикле ... Я просто упростил это для моего примера.)

$(document).ready(function() { 

    getAllUserGroups(); 

    var groupToCheck1 = "PMO"; 
    var groupToCheck2 = "HR22"; 
    if (!checkUserGroups(groupToCheck1) || !checkUserGroups(groupToCheck2)) { 
     // do your job 
     alert("User do not exist in both " + groupToCheck1 + " and " + groupToCheck2 + " groups"); 
    } 
}); 

//simple verification 
function checkUserGroups(groupName) { 
    if (window.AllUserGroups.indexOf(groupName) == -1) { 
     return false; 
    } 
    return true; 
} 

//get and store all groups in the global var. 
function getAllUserGroups() { 
    window.AllUserGroups = ""; 
    $().SPServices({ 
     operation: "GetGroupCollectionFromUser", 
     userLoginName: $().SPServices.SPGetCurrentUser(), 
     async: false, 
     completefunc: function (xData) { 
      $(xData.responseXML).find("Group").each(function() { 
       var groupName = $(this).attr("Name"); 
       window.AllUserGroups += groupName + ";"; 
      }); 
     } 
    }); 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^