One thing that CRM 3.0 lacks is the ability to lock down fields, buttons, forms etc based on the security role of the user logged in. Ronald Lemmen has a great blog post that allows you to call out-of-the box Javascript code to accomplish this task. You can find the URL here. I've taken his original post that allows you to check for User's roles and went a step further and starting enabling/disabling fields, hiding fields, hiding buttons and other things that we'd like to lock down for certain users.
Javascript Function #1: getUserId()
This function executes a WhoAmI request in order to retrieve the GUID of the currently logged in user.
function getUserId()
{
try
{
var command = new RemoteCommand("SystemUser", "WhoAmI", "/MSCRMServices/");
var oResult = command.Execute();
if (oResult.Success)
{
return oResult.ReturnValue.UserId;
}
}
catch(e)
{
alert("Error while retrieving userid.");
}
return null;
}
Javascript Function #2: getUserRoles(userid)
This function takes the GUID of the user from the first script and it gets the list of all roles assigned to that user.
function getUserRoles(userId)
{
try
{
var command = new RemoteCommand("UserManager", "GetUserRoles");
command.SetParameter("userIds", "<guid>" + userId + "</guid>");
var oResult = command.Execute();
if (oResult.Success)
{
return oResult.ReturnValue;
}
}
catch(e)
{
alert("Error while retrieving roles.");
}
return null;
}
Javascript Function #3: userHasRole(userid,roleName)
This function takes takes the GUID of the logged in user and a string parameter where you specify the name of the role that you are looking for. It calls teh getUserRoles() function to retrieve the list of roles. Once the list of roles has been retrieved it loops through the array of user roles checking for the specific role passed to this function.
function userHasRole(userId, roleName)
{
result = getUserRoles(userId);
if (result != null)
{
var oXml = new ActiveXObject("Microsoft.XMLDOM");
oXml.resolveExternals = false;
oXml.async = false;
oXml.loadXML(result);
roleNode = oXml.selectSingleNode("/roles/role[name='" + roleName + "']");
if (roleNode != null)
{
if (roleNode.selectSingleNode("roleid[@checked='true']") != null)
return true;
}
}
return false;
}
Javascript Function #4: currentUserHasRole(rolename)
This is the function that you would call from you Javascript to determine whether or not the user has the role that you are looking for. This calls the other functions and will return true if the user has the role otherwise it will return false/null if they don't.
function currentUserHasRole(roleName)
{
userId = getUserId();
return userHasRole(userId, roleName);
}
Now that we have the primary functions involved in accomplishing field-level security in Microsoft CRM, we can put these scripts to the test.
Part II - Locking Down Fields
Part III - Showing/HIding Fields
Part IV - Hiding Buttons/Navigation
Hopefully, Part II will be published by the end of this week.