Я нашел отличное сообщение о том, как узнать, является ли пользователь частью одной группы в 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');
}
});
В настоящее время я использую только одну группу. Когда мне нужно сложнее, я использую SPServices. Я надеюсь, что кто-то может сделать предложение, что я могу опубликовать полный ответ для других, чтобы найти. – H2O