Dynamics 365: Check if the current user has specific role

 

Javascript

Dynamics 365: Check if the current user has specific role

You often need to check in your client script if the current user has a special security role, for instance in a custom rule as part of a ribbon enable rule.

Here is a short code snippet that can be used for checking if the current user contains the security role with a specific name:

Javascript:

function hasCurrentUserRole(roleName){
  let hasRole = false;
  let roles = Xrm.Utility.getGlobalContext().userSettings.roles;
  roles.forEach(x => {
                if (x.name === roleName) {
                    hasRole = true;
                    return;
                }
               });
   return hasRole;
}

TypeScript:

static hasCurrentUserRole(roleName: string): boolean {
   let hasRole = false;
   let roles = Xrm.Utility.getGlobalContext().userSettings.roles;
   roles.forEach(x => {
                if (x.name === roleName) {
                    hasRole = true;
                    return;
                }
               });
   return hasRole;
}

In case you want to check the security role by its id, you can do it as follows. Keep in mind that the id’s from the roles collection contains the curly braces:

function hasCurrentUserRole(roleId){
  let hasRole = false;
  let roles = Xrm.Utility.getGlobalContext().userSettings.roles;
  roles.forEach(x => {
                if (x.id === roleId) {
                    hasRole = true;
                    return;
                }
               });
   return hasRole;
}

Here are some links for more information:

https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#roles

Data protection
, Owner: (Registered business address: Germany), processes personal data only to the extent strictly necessary for the operation of this website. All details in the privacy policy.
Data protection
, Owner: (Registered business address: Germany), processes personal data only to the extent strictly necessary for the operation of this website. All details in the privacy policy.