Wednesday, 18 May 2016

Check Roles of a user using Java-script

Check Roles of a user using Java-script 



//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 Role-name based on RoleId

function GetRoleName(roleId) {
   var serverUrl = Xrm.Page.context.getClientUrl();
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;
}

No comments:

Post a Comment