Thursday 29 November 2012

Add/Remove/Check Current User Against a Specific Group

//Check if current user is in a specific group
function isCurrentUserInGroup(groupId, funUserInGroup, funUserNotInGroup, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser, 'Id', 'LoginName');
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    var users = group.get_users();
    ctx.load(users);
 
    ctx.executeQueryAsync(function (sender, args) {
        //See whether the user exists
        var userFound = false;
        var userEnumerator = users.getEnumerator();
        while (userEnumerator.moveNext() && !userFound) {
            var user = userEnumerator.get_current();
            if (user.get_id() == currentUser.get_id()) {
                //User exists in the group
                userFound = true;
                if (funUserInGroup != null)
                    funUserInGroup();
            }
        }
        //User doesn't exist in the group
        if (!userFound && (funUserNotInGroup != null))
            funUserNotInGroup();
 
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 
//Add current user to specific group
function addCurrentUserToGroup(groupId, funOnSuccess, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser);
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    ctx.load(group);
    group.get_users().addUser(currentUser);
 
    ctx.executeQueryAsync(function (sender, args) {
        if (funOnSuccess != null)
            funOnSuccess(sender, args);
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 
//Remove current user from specific group
function removeCurrentUserFromGroup(groupId, funOnSuccess, funOnError) {
    var ctx = new SP.ClientContext.get_current();
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser);
    var group = ctx.get_web().get_siteGroups().getById(groupId);
    ctx.load(group);
    group.get_users().remove(currentUser);
 
    ctx.executeQueryAsync(function (sender, args) {
        if (funOnSuccess != null)
            funOnSuccess(sender, args);
    }, function (sender, args) {
        if (funOnError != null)
            funOnError(sender, args);
    });
}
 

No comments:

Post a Comment