SharePoint Add-in Client Side check if current user is in a group

Wanted to add some client side validation for my SharePoint hosted add-in (app, addin) to check whether a user was in an HR group. If the user is in the group then the proper interface will show, otherwise a message will display. Obviously you should do server side validation on your API calls or server side code as well if it's sensitive information. I've only tested this with side loading an app, it will probably require a certain level of permissions on app install.. Will update when I get that far 🙂 

var context;
var currentUser = null;
var userGroups;
var permissionsToView = false;

$(document).ready(function () {
    getCurrentUser();
});

function getCurrentUser() {
    var context = new SP.ClientContext.get_current();
    var website = context.get_web();
    currentUser = website.get_currentUser();
    userGroups = currentUser.get_groups();
    context.load(currentUser);
    context.load(userGroups);
    context.executeQueryAsync(Function.createDelegate(null, onQuerySucceeded), Function.createDelegate(null, onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    var groupsEnum = userGroups.getEnumerator();
    while (groupsEnum.moveNext()) {
        var group = groupsEnum.get_current();
        if (group.get_title() == "My Group Name") {
            permissionsToView = true;
        }
    }

    if (permissionsToView) {
        // yay can see!
    }
    else {
        $('.no-permissions').show(); // show some sort of no permissions message
    }
}

function onQueryFailed(sender, args) {
    $(".error").html('Request failed ' + args.get_message() + '\n' + args.get_stackTrace());
    $(".error").show();
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *