Wednesday, 26 February 2014

Guide on how to check a users Security Roles in 2011/2013 javascript

Helpfull Guide Outlined here
http://lakshmanindian.wordpress.com/2012/05/23/check-user-security-role-in-crm-2011-using-jscript/

Pasted  :
Check User Security Role in CRM 2011
Sometimes we get a requirement to check user security role and based on the result we need to perform certain operations. Here is the CRM 2011 Jscript code to check whether the user has a particular role or not.
We need to add “jquery1.4.1.min”(or laest version available) and “json2″ in the entity form, to perform a ODATA call as shown below. You can get those two files from the sdk.
Path – \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts
The Following code checks whether the “Activity Feeds” security role exists for the user or not and gets alert with true or false on onload jscript event. The functions CheckUserRole and FetchUserRoleIdWithName can be put in a sepertate js webresource it can be used across many entities
function onload(){
   // returns true if the given security role exists for the user, else returns false
   alert(CheckUserRole("Activity Feeds", Xrm.Page.context));
}

// This method takes SecurityRole Name and context as parameters
function CheckUserRole(roleName, context) {
   var userHasRole = false;

   //get the current roles for the user
   var userRoles = context.getUserRoles();

   //get the roleids with the rolename
   //the roleids can be multiple for multiple business units
   var roleIdArray = FetchUserRoleIdWithName(roleName, context);
   for (var userRole in userRoles) {
      if (jQuery.inArray(userRoles[userRole], roleIdArray) != -1){
         userHasRole = true;
         break;
      }
   }
   return userHasRole;
}

// Checks whether the security role exists in the system by using ODATA call
function FetchUserRoleIdWithName(roleName, context) {
   var serverUrl = Xrm.Page.context.getServerUrl();
   var oDataUri = serverUrl +  "/XRMServices/2011/OrganizationData.svc/RoleSet?$filter=Name eq '" + roleName + "'&$select=RoleId";
   var jSonArray = new Array();

   jQuery.ajax({
      type: "GET",
      contentType: "application/json; charset=utf-8",
      datatype: "json",
      url: oDataUri,
      async: false,
      beforeSend: function (XMLHttpRequest) {
         //Specifying this header ensures that the results will be returned as JSON.
         XMLHttpRequest.setRequestHeader("Accept", "application/json");
      },
      success: function (data, textStatus, XmlHttpRequest) {
         if(data && data.d != null){
            for(var count =0; count < data.d.results.length; count++){
               jSonArray.push(data.d.results[count].RoleId);
            }
         }
      },
      error: function (XmlHttpRequest, textStatus, errorThrown) {
         alert("Error :  has occured during retrieval of the role " + roleName);
      }
   });
   return jSonArray;
}

No comments:

Post a Comment