Thursday, June 14, 2012

Use SharePoint 2010 JavaScript (ECMAScript) Client Object Model to check current users permissions

The JavaScript Object Model is a very powerful tool to a SharePoint Developer if you know how to use it properly. Unfortunately there isn't that much information out there about it and searching for examples often leads you to C# style SharePoint Object Model code which is similar but not the same...

If you are new to it and want to learn more or play around with some working examples check these out!

I struggled to get this to work for longer than I would like to admit so I thought I would post it here to alleviate future headaches and in hopes that it helps someone else.

My requirement was to check the permission of the current user using The JavaScript Client Object Model and do "something"

So here is what I ended up with.

 <script type='text/javascript'>  
  ExecuteOrDelayUntilScriptLoaded(checkifUserHasEditListItems, "sp.js");  
 function checkifUserHasEditListItems ()   
 {  
  context = new SP.ClientContext.get_current();  
  web = context.get_web();  
  this._currentUser = web.get_currentUser();  
  context.load(this._currentUser);  
  context.load(web,'EffectiveBasePermissions');  
  context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));  
 }  
 function onSuccessMethod(sender, args)   
 {  
  if (web.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems))  
  alert('User has editListItems');  
  else  
  alert('no dice');  
 }  
 </script>  


You can dump this in a CEWP or include it in a .js file that you already have...either way it will prompt you with an alert (obviously the alert is just a placeholder for wonderful things to come)

No comments:

Post a Comment