Thursday, April 23, 2015

Check current user exists in a group using an AJAX call

$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('Site Members')/Users?         $filter=Id eq " + _spPageContextInfo.userId,
    type: "GET",
    cache: true,
    async: false,
    headers:{
        "ACCEPT": "application/json;odata=verbose"
    },
    success: function (data) {
  if (data.d.results[0] != undefined) {
        //user is a member
}
    },
    error: function () {
    }
});

Check current user exists on a group and hiding links using client object model

var userGroups;
function CheckPermissions(){
    var clientContext = new SP.ClientContext.get_current();
    var currentUser = clientContext.get_web().get_currentUser();
    clientContext.load(currentUser);
    userGroups = currentUser.get_groups();
    clientContext.load(userGroups);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onCheckPermissionSucceeded),
       Function.createDelegate(this, this.onCheckPermissionFailed));
}
function onCheckPermissionSucceeded(sender, args) {
    var groupsEnumerator = userGroups.getEnumerator();
    while (groupsEnumerator.moveNext()) {
  var group= groupsEnumerator.get_current();
  if(group.get_title() == "Site Members") {
  $("li a:contains('Link1')").hide();
$("li a:contains('Link2')").hide();
break;
  }
}
}  
function onCheckPermissionFailed(sender, args) {
  console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}