We have added a AD group to SharePoint users group. Now when we login with user, we want to check permission for the logged in AD user.
Unfortunately, the SPGroup.ContainsCurrentUser
property that you would use for this in server-side code is not accessible through the JavaScript client object model (at least not in SP2010 and 2013).
One potential workaround is to exploit a combination of two properties that you can access on groups via the JavaScript client object model: OnlyAllowMembersViewMemberhip
and CanCurrentUserViewMembership
.
If the current user can view group membership for a group that is only set to allow group members to do so, we can assume the user is a group member.
var clientContext = new SP.ClientContext();
var groupId = 5; // the group membership ID for the group you want to check
var group = clientContext.get_web().get_siteGroups().getById(groupId);
clientContext.load(group,"CanCurrentUserViewMembership");
clientContext.load(group,"OnlyAllowMembersViewMembership");
clientContext.executeQueryAsync(
function(sender,args){
var isMemberOfGroup = group.get_canCurrentUserViewMembership() && group.get_onlyAllowMembersViewMembership();
if(isMemberOfGroup){
doSomething();
}
},
function(sender,args){alert("Whoops! "+args.get_message());}
);
This approach will only work if you've set the groups to only be visible to members, and it'll always return a false positive if you have elevated access, such as if you're a site collection administrator or the group owner.
If you want to apply the above logic to check the current user's membership in all groups on the site (instead of specifying a group by its ID), you can use the modified JavaScript code below.
var clientContext = new SP.ClientContext();
var groups = clientContext.get_web().get_siteGroups()
clientContext.load(groups,"Include(CanCurrentUserViewMembership,OnlyAllowMembersViewMembership,Title)");
clientContext.executeQueryAsync(
function(sender,args){
var groupIterator = groups.getEnumerator();
var myGroups = [];
while(groupIterator.moveNext()){
var current = groupIterator.get_current();
var isMemberOfGroup = current.get_canCurrentUserViewMembership() && current.get_onlyAllowMembersViewMembership();
if(isMemberOfGroup){
myGroups.push(current.get_title()); // this example adds group titles to an array
}
}
alert(myGroups); // show the array
},function(sender,args){"Whoops! "+alert(args.get_message());});
For your requirements you may not even need programmatic access to the group membership. You could just set audience targeting on the web parts that you want to be visible only to certain groups; audience targeting should respect AD group membership.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With