locked
Retrieve user name and and security role for that user RRS feed

  • Question

  • I need to disable a field for users who don't have a certain security role via javascript.

    So far I have got the user ID of the person:

    // Get user ID
    var userID = Xrm.Page.context.getUserId();
    alert (userID);

    Searching for the answer on the forums I can see various examples such as:

     // Set Global Variables
      serverUrl = context.getServerUrl();
      userId = context.getUserId();
      ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    
      var retrieveReq = new XMLHttpRequest();
      retrieveReq.open("GET", ODataPath + "/RoleSet?$select=Name&$filter=RoleId eq guid'" + roleId + "'", true);
      retrieveReq.setRequestHeader("Accept", "application/json");
      retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      retrieveReq.onreadystatechange = function () {
        retrieveRoleNameReqCallBack(this);
      };
      retrieveReq.send();

    However this and the other examples fail - I am new to javascript so a little out of my depth at the moment.

    regards,

    Matt

    Wednesday, September 25, 2013 3:06 PM

Answers

  • As before all I get is Access Denied, when I run the code???

    After much scratching of head and googling I had to change serverurl line to

    var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

    This solved the access is denied error message.

    Just need to get my head around the code now to start understanding what is going on

    regards,

    Matt

    • Marked as answer by Matt_Hirst_UK Thursday, September 26, 2013 1:05 PM
    Thursday, September 26, 2013 1:05 PM

All replies

  • Try this code:-

    // Retrieving current login user security roles by using CRM client API method Xrm.Page.context.getUserRoles(); 
    var jj_UserSecurityRoles = Xrm.Page.context.getUserRoles();
     
    // Security role GUID (You can get it by opening Security Role record copy web address and go to the website 
     
    var jj_CustomerServicesRoleId = “{E324246D-B8AF-E011-AA34-C95682B33448}”; 
    var jj_UserHaveSecurityRole = false; 
     
    // Checking if Security Role Id found in User Security Roles 
    for (var x = 0; x < UserSecurityRoles.length; x++) { 
     
        if (UserSecurityRoles[x] == jj_CustomerServicesRoleId) { 
           jj_UserHaveSecurityRole = ture;     
        } 
    } 
     
    if (jj_UserHaveSecurityRole == false) { 
       throw new exception (“User has not been assigned Customer Service security role.”) 
    } 

    Also check:-

    http://mscrmblogger.com/2009/09/30/hide-fields-or-tabs-by-role-with-javascript/


    Regards Faisal



    • Edited by Faisal Fiaz Wednesday, September 25, 2013 3:44 PM
    Wednesday, September 25, 2013 3:41 PM
  • Matt,

    Two things are required to determine if you have an appropriate role.

    1.  All the role ID's assigned to the current user which can be found with the following.

    Xrm.Page.context.getUserRoles();
    2.  The ID of the role you care about.  This can be found either by

       a.  Querying ahead of time and hard coding the id as in Faisal's example (easiest, but upgrades and a few other things will require re-doing your code) or....

       b.  Querying every time to get the current id of the role by name (more complicated, but won't break each time you upgrade).

    If you go with option a, here is a good tutorial on retrieving that id (but make sure you pull up the roll in your browser, not the entity you are working with)

    http://crmbusiness.wordpress.com/2011/02/21/crm-2011-quick-way-to-find-a-guid-using-a-crm-form/

    If you go with option b, this is a good tutorial.  If you still get exceptions, you need to post the line it's failing on and the exception you are getting.

    http://rajeevpentyala.wordpress.com/2011/08/05/check-user-role-in-crm-2011-using-jscript/


    Troy

    Wednesday, September 25, 2013 9:16 PM
  • I have cut and pasted the code from option b, with an intention of running it then working out how it does what it does, however I get the following error:

    Microsoft Dynamics CRM Error Report Contents
    
    <CrmScriptErrorReport>
      <ReportVersion>1.0</ReportVersion>
      <ScriptErrorDetails>
       <Message>Access is denied.
    </Message>
       <Line>109</Line>
       <URL>/_forms/FormScript.js.aspx?FormName=crmForm&formid=66158f62-b004-4523-8124-47091c6698bc&fver=1024365870&isbulkedit=false&ver=-1008183168</URL>
       <PageURL>/userdefined/edit.aspx?_gridType=1084&etc=1084&id=%7b2CCA086A-C825-E311-8ECF-02BF0A86F1E1%7d&pagemode=iframe&preloadcache=1380185025397&rskey=366350440</PageURL>
       <Function></Function>
       <CallStack>
       </CallStack>
      </ScriptErrorDetails>
      <ClientInformation>
       <BrowserUserAgent>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)</BrowserUserAgent>
       <BrowserLanguage>en-us</BrowserLanguage>
       <SystemLanguage>en-us</SystemLanguage>
       <UserLanguage>en-gb</UserLanguage>
       <ScreenResolution>1280x1024</ScreenResolution>
       <ClientName>Web</ClientName>
       <ClientTime>2013-09-26T09:43:52</ClientTime>
      </ClientInformation>
      <ServerInformation>
        <OrgLanguage>1033</OrgLanguage>
        <OrgCulture>2057</OrgCulture>
        <UserLanguage>1033</UserLanguage>
        <UserCulture>2057</UserCulture>
        <OrgID>{243A0FF8-F595-E211-96EA-02BF0A86F1E1}</OrgID>
        <UserID>{82BC61EF-740C-E211-A4D0-02BF0A86F1E1}</UserID>
        <CRMVersion>5.0.9690.2865</CRMVersion>
      </ServerInformation>
    </CrmScriptErrorReport>
    

    Message says Access is denied does this need I require certain permissions to run this?  If so i need this to be able to be run irrespective of what type of user is running the code.

    Any pointers?

    Matt

    Thursday, September 26, 2013 8:48 AM
  • Debugging further it seems to fail at this line:

    service.open("GET",oDataEndpointUrl, false);

    The oDataEndpointUrl returns this:

    http:// server /XRMServices/2011/OrganizationData.svc/RoleSet?$top=1&$filter=Name eq 'System Administrator'

    with the server being loadbalancer/Testserver which I am running this from.

    regards,

    Matt

    Thursday, September 26, 2013 9:14 AM
  • I use the following function

    function UserHasRole(roleName)
    {
        var serverUrl = Xrm.Page.context.getServerUrl();
        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "RoleSet?$filter=Name eq '" + roleName + "'&$select=RoleId";
        var service = GetRequestObject();
        if (service != null)
        {
            service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json, text/javascript, */*");
            service.send(null);
            var requestResults = eval('(' + service.responseText + ')').d;
            if (requestResults != null && requestResults.results.length > 0)
            {
                for (var i = 0; i < requestResults.results.length; i++)
                {
                    var role = requestResults.results[i];
                    var id = role.RoleId;
                    var currentUserRoles = Xrm.Page.context.getUserRoles();
                    for (var j = 0; j < currentUserRoles.length; j++)
                    {
                        var userRole = currentUserRoles[j];
                        if (GuidsAreEqual(userRole, id)==true)
                        {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
     }

    which returns either a true or false. So calling:

    var isUserSysAdmin = UserHasRole("System Administrator");

    puts either true or false in the variable. You've got the get the title of the role spot on though.

    You'll also need the following function:

    function GuidsAreEqual(guid1, guid2)
    {
        var isEqual = false;
        if (guid1 == null || guid2 == null)
            isEqual = false;
        else
            isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
        return isEqual;
    }

    • Edited by Jon_Evans Thursday, September 26, 2013 11:38 AM Forgot vital information
    Thursday, September 26, 2013 11:32 AM
  • As before all I get is Access Denied, when I run the code???

    After much scratching of head and googling I had to change serverurl line to

    var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();

    This solved the access is denied error message.

    Just need to get my head around the code now to start understanding what is going on

    regards,

    Matt

    • Marked as answer by Matt_Hirst_UK Thursday, September 26, 2013 1:05 PM
    Thursday, September 26, 2013 1:05 PM
  • Matt,

    The value returned by Xrm.getServerUrl is configured in the Web Address tab of the deployment properties in the Crm Deployment Manager tool.  Be aware that the method you selected doesn't work in all cases either.  If it's working for now though, that's great.


    Troy

    Thursday, September 26, 2013 2:07 PM
  • Troy,

    You are right I do have an issue, for certain users the code doesn't work - even when I can see they are set to Sales Managers.

    function SetApproved()
    {
        // returns true if user has the role
        var isUserSysAdmin = UserHasRole("Sales Manager");
        
        //alert("User is Sales Manager" + isUserSysAdmin);
        
        if (isUserSysAdmin)
        {
            var SetControl = Xrm.Page.ui.controls.get("approved_yn");
    
            SetControl.setDisabled(false);
        }
        else
        {
            var SetControl = Xrm.Page.ui.controls.get("approved_yn");
    
            SetControl.setDisabled(true);
        }
    
    }
    
    
    function UserHasRole(roleName)
    //Function to check if a user has a specific role or not
    {
        var serverUrl = document.location.protocol + "//" + document.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "RoleSet?$filter=Name eq '" + roleName + "'&$select=RoleId";
        var service = GetRequestObject();
    
        if (service != null)
        {
            service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json, text/javascript, */*");
            service.send(null);
            var requestResults = eval('(' + service.responseText + ')').d;
            if (requestResults != null && requestResults.results.length > 0)
            {
                for (var i = 0; i < requestResults.results.length; i++)
                {
                    var role = requestResults.results[i];
                    var id = role.RoleId;
                    var currentUserRoles = Xrm.Page.context.getUserRoles();
                    for (var j = 0; j < currentUserRoles.length; j++)
                    {
                        var userRole = currentUserRoles[j];
                        if (GuidsAreEqual(userRole, id)==true)
                        {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
     }
    
    function GetRequestObject()
    {
        if (window.XMLHttpRequest)
        {
            return new window.XMLHttpRequest;
        }
        else
        {
            try
            {
                return new ActiveXObject("MSXML2.XMLHTTP.3.0");
            }
            catch (ex)
            {
                return null;
            }
        }
    }
    
    function GuidsAreEqual(guid1, guid2)
    // function to compare guids
    {
        var isEqual = false;
        if (guid1 == null || guid2 == null)
            isEqual = false;
        else
            isEqual = guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase();
        return isEqual;
    }

    Any ideas what the issue could be, they receive no error messages as such, it just doesn't see them as a sales manager?

    Matt

    Friday, September 27, 2013 8:36 AM
  • Just discovered the error is to do with the security roles not having permissions to view Security Roles, once this was set correctly it all worked perfect.

    regards,

    Matt

    Friday, September 27, 2013 10:30 AM