Get Login User Role name(s) in JavaScript using OData in Dynamics CRM 2011

Here is the sample JavaScript code to get login user role.
Make sure you have added jquery-1.9.1.min.js and JSON2.js in Entity form libraries.If not you can download these from following URL’s
http://jquery.com/download/
http://www.json.org/js.html

//Check login User has 'System Administrator' role
function CheckUserRole() {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
         var userRoleId = currentUserRoles[i];
	var userRoleName = GetRoleName(userRoleId);
        if (userRoleName == "System Administrator") {
            return true;
        }
    }
    return false;
}

//Get Rolename based on RoleId
function GetRoleName(roleId) {
    //var serverUrl = Xrm.Page.context.getServerUrl();
    var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
    var roleName = null;
    $.ajax(
        {
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                roleName = data.d.results[0].Name;
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
        }
    );
    return roleName;
}

6 thoughts on “Get Login User Role name(s) in JavaScript using OData in Dynamics CRM 2011

  1. Hi,
    to avoid multiple request to server it would be better to get the RoleId of the role to check and check for that instead of role name.

    userHasRole = function (roleName) {
    var searchRoleId = xrmHelper.getRoleId(roleName);
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
    var userRoleId = currentUserRoles[i];
    if (userRoleId == searchRoleId) {
    return true;
    }
    }
    return false;
    };

  2. Moi aussi, j’ai un problème qui va dans ce sens. Pouvez-vous m’aider à trouver la solution ?
    En fait, je cherche à verrouiller un champ recherche et donner l’accès uniquement à l’utilisateur qui a le rôle Manager. A chaque fois, je reçois comme message :
    Roleid is not defined at getRoleName.
    Voici mon code :
    function sample() {
    var RoleName;
    var count = 0;
    var currentUserRoles = Xrm.Page.context.getUserRoles(); //CurrentUserRoles contains logined user Secuirty Roles Guids.
    for (var i = 0; i = 1) {
    Xrm.Page.GetControl(“statuscode”).setDisabled(false); //Unlock Job Title field
    }
    else {
    Xrm.Page.GetControl(“statuscode”).setDisabled(true); // Lock Job Title field

    }
    }
    }
    function getRoleName() {
    var name;
    var req = new XMLHttpRequest();
    req.open(“GET”, Xrm.Page.context.getClientUrl() + “/api/data/v8.2/roles?$select=name&$filter=roleid eq ” + Roleid, false);
    req.setRequestHeader(“OData-MaxVersion”, “4.0”);
    req.setRequestHeader(“OData-Version”, “4.0”);
    req.setRequestHeader(“Accept”, “application/json”);
    req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
    req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
    }
    req.onreadystatechange = function () {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var results = JSON.parse(this.response);
    for (var i = 0; i < results.value.length; i++) {
    name = results.value[i]["name"];
    }
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }

    };
    req.send();
    return name;

    }

  3. I too have a problem that goes in this direction. Can you help me find the solution?
    In fact, I try to lock a search field and give access only to the user who has the role Manager. Each time, I receive as a message:
    Roleid is not defined at getRoleName.
    This is my code :

    function sample() {
    var RoleName;
    var count = 0;
    var currentUserRoles = Xrm.Page.context.getUserRoles(); //CurrentUserRoles contains logined user Secuirty Roles Guids.
    for (var i = 0; i = 1) {
    Xrm.Page.GetControl(“statuscode”).setDisabled(false); //Unlock Job Title field
    }
    else {
    Xrm.Page.GetControl(“statuscode”).setDisabled(true); // Lock Job Title field

    }
    }
    }
    function getRoleName() {
    var name;
    var req = new XMLHttpRequest();
    req.open(“GET”, Xrm.Page.context.getClientUrl() + “/api/data/v8.2/roles?$select=name&$filter=roleid eq ” + Roleid, false);
    req.setRequestHeader(“OData-MaxVersion”, “4.0”);
    req.setRequestHeader(“OData-Version”, “4.0”);
    req.setRequestHeader(“Accept”, “application/json”);
    req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
    req.setRequestHeader(“Prefer”, “odata.include-annotations=\”*\””);
    }
    req.onreadystatechange = function () {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var results = JSON.parse(this.response);
    for (var i = 0; i < results.value.length; i++) {
    name = results.value[i]["name"];
    }
    } else {
    Xrm.Utility.alertDialog(this.statusText);
    }

    };
    req.send();
    return name;

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s