29

I would like to check with JavaScript if the current logged user is in a specified and specific group (for example called "Admins Group").

How can I do?

Thanks

Nicole
  • 476
  • 2
  • 13
Pepozzo
  • 1,073
  • 2
  • 15
  • 36

5 Answers5

42

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

Vadim Gremyachev
  • 42,498
  • 3
  • 86
  • 167
18

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);
}
Lars Lynch
  • 396
  • 3
  • 4
  • 4
    Cannot get enumerator on userGroups in the OnQuerySucceeded with "this". When I remove "this", everything works. I like your approach, but why do we need all of those "this"?? I removed them all and everything works well. – Florian Leitgeb Dec 21 '15 at 12:27
  • 2
    You'll have to bind this: clientContext.executeQueryAsync(OnQuerySucceeded.bind(this)) – Anders Aune Jun 14 '16 at 05:31
  • 1
    what is OnResult( ... ) ? an internally function? – user3080110 Aug 25 '17 at 14:11
7

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*****//
            }
        });
    })
Ahmed Masud
  • 552
  • 1
  • 6
  • 16
  • This does not seem to work in SharePoint Foundation 2013 - I get XML back not JSON. Here is the start of what I get: b45b14da-2c89-45c2-bea6-fbcacf6b3d3e – George M Ceaser Jr Aug 03 '17 at 21:56
  • Are you accessing the url from browser ? if yes, then it will return the xml or you can change the request header using postman or any extension. – Ahmed Masud Aug 04 '17 at 17:47
5

Function:

function isCurrentUserMemberOfGroup(groupName) {
    var userIsInGroup = false;
    $.ajax({
        async: false,
        headers: { "accept": "application/json; odata=verbose" },
        method: "GET",
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser/groups",
        success: function (data) {
            data.d.results.forEach( function (value) {
                if (value.Title == groupName) {               
                     userIsInGroup = true;
                }
            });
        },
        error: function (response) {
            console.log(response.status);
        },
    });    
    return userIsInGroup;
}

Usage:

var isAdmin = isCurrentUserMemberOfGroup("Admins Group");
Sergey
  • 51
  • 1
  • 2
0

Personnaly, the method with the SP.ClientContext didn't worked. So I used an asynchronous request to the Web API of SP like this :

$.getScript("/_layouts/15/SP.UserProfiles.js");
SP.SOD.executeOrDelayUntilScriptLoaded(checkAdminRights, "SP.UserProfiles.js");

function checkAdminRights() {
    var userId = _spPageContextInfo.userId;
    var groupId = 7;
    var requestHeaders = { "accept" : "application/json; odata=verbose" };

    $.ajax({
        url : _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(" + groupId + ")/users/getbyid(" + userId + ")",
        contentType : "application/json;odata=verbose",
        headers : requestHeaders,
        success : userAdmin,
        error : userNotAdmin
    });
    function userAdmin(data, request){
        // if we reach here, the current user belongs to the group Id 7 for the example
        var userName = data.d.LoginName;
    }
    function userNotAdmin(error) {
        console.log(error.textStatus);
    }
}

For my example, I checked if current user belongs to the group of id 7 (sharepoint admin), if it's the case, ajax request is a success, then I do my process. If the user is not found in the group, function fails.

Alex
  • 327
  • 1
  • 3
  • 16
  • 2
    you can also pass by "...sitegroups/getbyname("")/users ..." if you don't want to get the group by id, but by it name. – Alex Nov 20 '14 at 16:51