Check if current user is present in SharePoint Group using REST API

Hello friends. In this article, we will write a jQuery code for checking if the current logged in user is present in the SharePoint group.

How to check if current user present in SharePoint Group

We will check, if the user is present in the "Application Owners" group or not.

/** Check if the current user is in Owners group **/
function isOwnerGroupMember() {
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('Application Owners')/Users?$filter=Id eq " + _spPageContextInfo.userId,
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose"
        },
        success: function(data) {
            if (data.d.results.length == 0) {
                console.log("User not in group : Application Enhancement Owners");                
            } else {
                console.log("User in group : Application Enhancement Owners");                
            }
        },
        error: function(err) {
            console.log("Error while checking user in Owner's group");            
        }
    });
}

In this above function, we are calling response for the users present in "Application owners" group and filtering users with currently logged in user id (_spPageContextInfo.userId).

If the user is present, it should provide a response with only one user else 0. We are checking this condition using if statement (data.d.results.length).

If data.d.results.length is 0, it means the user is not present else it is present.

Post a Comment

0 Comments