Friday, February 10, 2017

Check whether a user exists in a SharePoint group using Rest Api?

Solution

The rest query url. This was tested in SharePoint Online

var isMember = false;

var userId = _spPageContextInfo.userId;// _spPageContextInfo.userId is current logged in user

var groupName = "Name of the group";

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('"+ groupName +"')/Users?$filter=Id eq "+ userId ;
Once the results are received we have check the length of the results as below.

if(result.data.d.results.length >0){
                 isMember = true;
                 }
     

The full code is below. Please note that I have used deferred in Angular JS.

  function getIsCurrentUserInGroup()
    {
        var isMember = false;
 var deferred = $q.defer();
 var userId = _spPageContextInfo.userId;// _spPageContextInfo.userId is current logged in user
 var groupName = "Name of the group";
        var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('"+ groupName +"')/Users?$filter=Id eq "+ userId ;
        $http({
            url: url,
            method: "GET",
            contentType: "application/json;odata=verbose",
            headers: { "Accept": "application/json; odata=verbose" }
        }).then(function (result) {
            
           if(result.data.d.results.length >0)
 {
  isMember = true;
 }
            deferred.resolve(isMember );
        }, function (error) {
            deferred.reject('Request failed. ' + errorCode.get_message() + '\n' + errorCode.get_stackTrace());
        });

        return deferred.promise;
        
     }

No comments:

Post a Comment