moussa-e
8/16/2016 - 7:56 AM

CRM 2016 #Security #Roles #JavaScript #CRM2016 #MoussaElAnnan

CRM 2016 #Security #Roles #JavaScript #CRM2016 #MoussaElAnnan

/* Usage
   var cmRole = checkUserRole("DP - Lead", "RoleSet", "Name");
*/
 
 /* This function will get all the user's security role Id, 
 * passing security role id to get the security role name. If it match, it is true otherwise false.
 * @params roleName The role name.
 * @params roleSet The roleset.
 * @params fieldtoRetrieve The field to retrieve.
 */
checkUserRole = function (roleName, roleSet, fieldToRetrieve) {
	var currentUserRoles = Xrm.Page.context.getUserRoles();
	for (var i = 0; i < currentUserRoles.length; i++) {
		var userRoleId = currentUserRoles[i];
		var userRoleName = getRoleName(roleSet, userRoleId, fieldToRetrieve);
		if (userRoleName === null) continue;
		//    if (userRoleName == roleName) {
		if (stringStartsWith(userRoleName, roleName)) {
			return true;
		}
	}
	return false;
}
/*
 * This function calling odata web service and get the each security role name.
 * @param roleSet The entity set.
 * @param userRoleId The record id.
 * @param fieldToRetrieve The field to retrieve.
 */
getRoleName = function (roleSet, userRoleId, fieldToRetrieve) {
	var roleName = null;
	XrmServiceToolkit.Rest.Retrieve(
	 userRoleId,
	roleSet,
	fieldToRetrieve,
	 null,
	 function (result) {
		 roleName = result.Name;
	 },
	 function (error) {
		 alert(error.message);
	 },
	 true
 );
	return roleName;
}
/*
 * Function slice a string using a prefix (used for searching).
 * @param string The string to search on.
 * @param The string prefix.
 */
stringStartsWith = function (string, prefix) {
	return string.toString().slice(0, prefix.length) === prefix;
}