- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
How to find out if a user has a specific role and only that role.
This function takes role name and user sys_id as checks if the user has only that role and no other roles. It returns response as true / false.
True = if user only has the specified role
Fast = if user has no role or any other roles or more than one role.
function hasRoleOnly(roleName, userId) {
var returnBol = false;
var roleList = getAllRoles(userId);
if (roleList.length() > 1 || roleList.length == 0 || JSUtil.nil(roleList)) {
returnBol = false;
}
if (roleList.length == 1) {
if (roleName == roleList[0]) {
returnBol = true;
}
}
return returnBol;
}
function getAllRoles(userId) {
var roleList = [];
var grUserRole = new GlideRecord('sys_user_has_role');
var query = 'user=' + userId;
grUserRole.addEncodedQuery(query);
grUserRole.query();
while (grUserRole.next()) {
roleList.push(grUserRole.role.name);
}
return roleList;
}
References : User Object Cheat Sheet - ServiceNow Guru
- 3,125 Views
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
