Sharepoint - Check if user is in a specified group
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:
function IsCurrentUserHasContribPerms()
{
IsCurrentUserMemberOfGroup("Members", function (isCurrentUserInGroup) {
if(isCurrentUserInGroup)
{
// The current user is in the [Members] group!
}
});
}
ExecuteOrDelayUntilScriptLoaded(IsCurrentUserHasContribPerms, 'SP.js');
Gist SP.IsCurrentUserMemberOfGroup.js
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);
}
This code worked for me, its simple and does the job
var url = _spPageContextInfo.webAbsoluteUrl +'/_api/web/currentuser/groups'
$.getJSON(url, function (data) {
$.each(data.value, function (key, value) {
if (value.Title == 'GroupName') {
//*****your code goes here*****//
}
});
})