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

3
  • I answered this on SO some time ago: [Using jQuery to assess logged in user group membership][1] [1]: stackoverflow.com/questions/8841985/…
    – Paul Leigh
    Commented Jan 7, 2014 at 16:14
  • Thanks @PaulLeigh but I can't use SPServices on my solution.
    – Pepozzo
    Commented Jan 7, 2014 at 16:18
  • 1
    Eeek, thats a first! Ok, well its just some very nice wrappers for the underlying Web Services call - UserGroup.GetGroupCollection, which you'll have to do the hard way with xmlNodes I guess.
    – Paul Leigh
    Commented Jan 7, 2014 at 16:37

5 Answers 5

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

7
  • the code doesn't work. the error is OnComplete function is not defined
    – user23771
    Commented Feb 18, 2014 at 19:35
  • 3
    @VeraCardoso, you are supposed to implement the OnComplete method yourself to do what you need to so with the response Commented Feb 18, 2014 at 19:58
  • 1
    great solution :)
    – Grzegorz Z
    Commented Feb 2, 2015 at 12:50
  • I dont think getByName() is available in 2010. When viewing the get_siteGroups() object there looks like only getById(). Commented Feb 26, 2015 at 20:24
  • That's right SP.GroupCollection.getByName function is not available in SP 2010, but you probably could find this answer helpful stackoverflow.com/a/22126724/1375553 (second example is compatible with SharePoint 2013/2010) Commented Feb 26, 2015 at 20:54
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);
}
3
  • 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. Commented Dec 21, 2015 at 12:27
  • 2
    You'll have to bind this: clientContext.executeQueryAsync(OnQuerySucceeded.bind(this)) Commented Jun 14, 2016 at 5:31
  • 1
    what is OnResult( ... ) ? an internally function? Commented Aug 25, 2017 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*****//
            }
        });
    })
2
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");
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.

1
  • 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
    Commented Nov 20, 2014 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.