locked
Get security role name using Javascript? RRS feed

  • Question

  • How to get security role name of logged in user using JavaScript?


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Thanks and Regards, Yogesh Vijay Mulay

    Friday, April 26, 2013 3:17 AM

All replies

  • Hi,

         Here is few good links for the same:

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

         Also following example does exactly that:

    function UserHasRole(roleName)
    {
        var serverUrl = Xrm.Page.context.getServerUrl();

        var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
        oDataEndpointUrl += "RoleSet?$top=1&$filter=Name eq '" + roleName + "'";

        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.length == 1)
            {
                var role = requestResults[0];

                var id = role.RoleId;

                var currentUserRoles = Xrm.Page.context.getUserRoles();

                for (var i = 0; i < currentUserRoles.length; i++)
                {
                    var userRole = currentUserRoles[i];

                    if (GuidsAreEqual(userRole, id))
                    {
                        return true;
                    }
                }
            }
        }

        return false;
    }


    Hope this helps.
     
    -----------------------------------------------------------------------
     Minal Dahiya
     
    If this post answers your question, please click "Mark As Answer" on the post and "Vote as Helpful"

    • Proposed as answer by Minal Dahiya Friday, April 26, 2013 3:36 AM
    Friday, April 26, 2013 3:36 AM
  • Otherwise if you don't already know the role names assigned the user - you can get them with this code:

    function GetUserRoles() {
        var roles = Xrm.Page.context.getUserRoles();
    
        for (var i = 0; i < roles.length; i++) {
            GetRole(roles[i]);
        }
    }
    
    function GetRole(roleid) {
        var serverUrl = Xrm.Page.context.getClientUrl();
        var oDataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc/RoleSet?$select=Name&$filter=RoleId eq guid'" + roleid + "'";
    
        var retrieveReq = new XMLHttpRequest();
        retrieveReq.open("GET", oDataSelect, false);
        retrieveReq.setRequestHeader("Accept", "application/json");
        retrieveReq.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        retrieveReq.onreadystatechange = function () {
            GetRoleData(this);
        };
        retrieveReq.send();
    }
    
    function GetRoleData(retrieveReq) {
        if (retrieveReq.readyState == 4) {
            if (retrieveReq.status == 200) {
                var retrieved = JSON.parse(retrieveReq.responseText).d;
                alert(retrieved.results[0].Name);
            }
        }
    }


    Jason Lattimer
    My Blog -  Follow me on Twitter -  LinkedIn

    Friday, April 26, 2013 3:40 AM
    Moderator
  • Hi,

    I never used OData.

    service.open("GET", oDataEndpointUrl, false);
            service.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
            service.setRequestHeader("Accept", "application/json, text/javascript, */*");
            service.send(null);

    At this step nothing happens. Do I need to enablel any settings in CRM or need to install anything in CRM to get working OData.


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Thanks and Regards, Yogesh Vijay Mulay

    Friday, April 26, 2013 5:11 AM
  • Hi Yogesh,

         You need to add JQuery reference to the form where you are using this. It is found in CRM 2011 SDK at following location.

    \sdk\samplecode\js\restendpoint\jqueryrestdataoperations\jqueryrestdataoperations\scripts.

        You just need jquery1.4.1.min file.

    You can find the SDK at the following link:

    http://www.microsoft.com/en-au/download/details.aspx?id=24004

         Here is the site where it has step by step:

    http://www.toplinestrategies.com/dotneters/technology/microsoft-crm-2011-odata-examples/?lang=en


    Hope this helps.
     
    -----------------------------------------------------------------------
     Minal Dahiya
     
    If this post answers your question, please click "Mark As Answer" on the post and "Vote as Helpful"

    • Proposed as answer by Minal Dahiya Friday, April 26, 2013 5:37 AM
    Friday, April 26, 2013 5:37 AM
  • Hi,

    As far as i know,you can use it as it is!It just set the custom http headers to the request.  And for reference,

    Go through ,

    http://blogs.infinite-x.net/2010/11/16/retreiving-user-roles-in-crm-2011/


    Sindu M


    • Edited by VidhiyaM Friday, April 26, 2013 5:42 AM
    Friday, April 26, 2013 5:37 AM
  • Hi Minal,

    I tried with the same.

    var role = requestResults[0]; 
    alert(role);
    var id = role.RoleId;

    I am getting role as undefined. Till this step it works perfect.

    Please guide.


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Thanks and Regards, Yogesh Vijay Mulay

    Friday, April 26, 2013 6:04 AM
  • Hi Yogesh,

         Please check the result variable. I suggest turn on client side debugging and walk through each line. Here is the link as to how to achieve this.

    http://social.technet.microsoft.com/wiki/contents/articles/3256.how-to-debug-jscript-in-microsoft-dynamics-crm-2011.aspx

    -Minal

    Friday, April 26, 2013 6:12 AM
  • Hi Yogesh,

    Here is the code to get the logged in user roles using Odata with Jquery

       //Get the Login User ID
       var loginuser = Xrm.Page.context.getUserId();
        var oDataEndpointUrl = "SystemUserSet?$select=systemuserroles_association&$expand=systemuserroles_association&$filter=SystemUserId eq guid'" + loginuser + "'";
        var requestResults = ODataCommonFunctions.GetDataUsingODataServiceWithJQuery(oDataEndpointUrl);
        if (requestResults != null && requestResults.results.length > 0) {
            for (var i = 0; i < requestResults.results[0].systemuserroles_association.results.length; i++) {
                var roleName = requestResults.results[0].systemuserroles_association.results[i].Name;
                if (roleName != null && roleName != "") 
    			{
    			 //Get all the Roles of the loginUser
                  alert(roleName);
                }
            }
        }
    	
    	
    // ========== OData Serivce - JQuery Request Functions Start ==========
    
    function GetDataUsingODataServiceWithJQuery(ODataSelect) {
        var resultOfGet = null;
        var CRMContext = GetContext();
        if (CRMContext != null) {
            var serverUrl = CRMContext.getServerUrl();
            var ODataEndpoint = "/XRMServices/2011/OrganizationData.svc";
            var ODataURL = serverUrl + ODataEndpoint + "/" + ODataSelect;
            try {
                $.ajax({
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    datatype: "json",
                    async: false,
                    url: ODataURL,
                    beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
                    success: function (data, textStatus, XmlHttpRequest) {
                        resultOfGet = data.d;
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        DisplayError("ODataService", "Fetch", textStatus + " - " + JSON.parse(XMLHttpRequest.responseText).error.message.value);
                        //resultOfGet = null;
                    }
                });
            } catch (e) {
                DisplayError("ODataService", "Fetch", e.description);
                //resultOfGet = null;
            }
        }
        return resultOfGet;
    }
    
    function GetContext() {
        var _context = null;
        if (typeof GetGlobalContext != "undefined")
            _context = GetGlobalContext();
        else if (typeof Xrm != "undefined")
            _context = Xrm.Page.context;
        return _context
    }
    
    
     function DisplayError(cntrl, func, err) {
        alert("Control : " + cntrl + "\nODataCommonFunctions.: " + func + "\nError : " + err);
    }
    

    Note:Please add "Jquery" and "json" file in form libraries.

    Hope this helps,

    Regards,

    Yusuf


    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer". Thanks and Regards, Mohammad Yusuf Ansari http://microxrm.blogspot.in

    Friday, April 26, 2013 7:13 AM
  • Hi Jason,

    What if I retrieved multiple User Roles (for example: System Administrator and System Customizer), how can I display both/all the retrieved roles in a single form field? I have no problem in setting a single user role on a field, but multiple, any input? Thanks

    Monday, May 27, 2013 7:08 AM
  • you can concatenate them to show in one field like below

    "FirstRole;"+"SecondRole"


    My Website | My Blog | Follow me on Twitter | My Facebook Page | Microsoft Dynamics CRM 2011 Application Design
    Make sure to "Vote as Helpful" and "Mark As Answer",if you get answer of your question.

    Monday, May 27, 2013 9:23 AM
    Moderator
  • Thanks a lot Jason. its work for me CRM 2013....:)


    Fahmeeda yaseen

    Thursday, November 28, 2013 8:33 AM