Pragya11
Mega Explorer

In Server side side we can use gs.hasRole("itil") to know if the logged in user has "itil" role. But this has an issue as for an admin it will return always true.

Instead use the below script to check the role

Script Include: userRoleUtility

var userRoleUtility = Class.create();
userRoleUtility.prototype = {
initialize: function() {
},

hasRole: function(user,role)
{
var userRole = new GlideRecord('sys_user_has_role');
userRole.addEncodedQuery('role.name='+role+'^user='+user);
userRole.query();
if(userRole.next())
{
return true;
}
else
{
return false;

}
},
type: 'userRoleUtility'
};

Server side script Usage

var user= new userRoleUtility();
gs.info(user.hasRole(gs.getUserID(),"itil"));

Comments
Ibrahim-Ben Far
Tera Contributor

Hi Pragya,

instead of GlideRecord-querying, you could GlideUser.getRoles():

use https://developer.servicenow.com/dev.do#!/reference/api/rome/server/no-namespace/c_GlideUserScopedAPI#r_SGU-getRoles?navFilter=getrol

Example: 

var roles = (gs.getUser().getUserByID(user).getRoles() +'').split(',');

for (var i = 0; i < roles.length; i++) {

    if (roles[i] == role) return true;

}

 

If that check should only apply to the current user you can leave out .getUserByID(user). 

 

This way you'd be utilizing the ServiceNow Cache a bit better and the code gets a bit slimmer.

 

Pragya11
Mega Explorer

gs.getUser().getUserByID(user).getRoles() does not work in scoped application

Version history
Last update:
‎12-13-2021 03:43 AM
Updated by: