Thursday, September 22, 2016

SharePoint 2010/2013 - Verify if current user is a member of a Group using group name (CSOM Javascript)

$(document).ready(function () {
    currentUserIsMemberOf("SharePoint Owners Group").done(function (result) {
        alert(result)
    });
});


var currentUserIsMemberOf = function (groupName) {
    var found = false; var dfd = $.Deferred(function () {
        SP.SOD.executeOrDelayUntilScriptLoaded(function () {
            context = new SP.ClientContext.get_current();
            allGroups = context.get_web().get_siteGroups(); c
            ontext.load(allGroups); context.load(allGroups, 'Include(Users)');
            context.executeQueryAsync(function () {
                var groupInfo; var groupsEnumerator = allGroups.getEnumerator();
                while (groupsEnumerator.moveNext()) {
                    var group = groupsEnumerator.get_current();
                    if (group.get_title() == groupName) {
                        var usersEnumerator = group.get_users().getEnumerator();
                        while (usersEnumerator.moveNext()) {
                            var user = usersEnumerator.get_current();
                            if (user.get_id() == _spPageContextInfo.userId) {
                                found = true;
                                break;
                            }
                        }
                    }
                } dfd.resolve(found);
            }, function () { dfd.reject(args.get_message()); });
        }, 'sp.js');
    }); return dfd.promise();
}

Ref Link: https://gist.github.com/robertosljunior/cc46d4447cf6d6b60c67/119d8f3d404c35e67af3d34bade5ea871e36400d

No comments:

Post a Comment