- Post History
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
on 12-13-2021 03:43 AM
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"));
- 22,913 Views

- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
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.
- Mark as Read
- Mark as New
- Bookmark
- Permalink
- Report Inappropriate Content
gs.getUser().getUserByID(user).getRoles() does not work in scoped application