User Criteria Advanced Script to check if user has any role

jlaue
Kilo Sage

Hello - I am working on creating a User Criteria record that checks if the logged in user has any role at all.  I have been through many Community posts that check if a user has a specific role (such as ITIL), but that can be accomplished just using the form options on the User Criteria record.  I am looking for help on User Criteria advanced script that checks to see if the user has any role at all, regardless of the role and then allow them to view the catalog item if they do have any role.  

 

Thanks!!

 

 

1 ACCEPTED SOLUTION

Nia McCash
Mega Sage
Mega Sage

A couple of options...

 

You can check that gs.getUser().getRoles() is empty. See https://developer.servicenow.com/dev.do#!/reference/api/tokyo/server_legacy/GUserAPI#GUser-getRoles?...

 

Or, you can query the sys_user_has_role table for the user and check there are no results returned (ie. there are no entries in the sys_user_has_role for the user meaning that the user has no roles).

View solution in original post

6 REPLIES 6

Mike_R
Kilo Patron
Kilo Patron

Try this

 

 

var userGR = new GlideRecord('sys_user');
userGR.get(user_id);
if (userGR.getValue('roles')) {
    answer = true;
} else {
    answer = false;
}

 

 

Mike_R_0-1673021891521.png

 

Thanks for the quick response!  I tried using the script provided, however users with or without a role cannot view the catalog item that I used this on. 

Nia McCash
Mega Sage
Mega Sage

A couple of options...

 

You can check that gs.getUser().getRoles() is empty. See https://developer.servicenow.com/dev.do#!/reference/api/tokyo/server_legacy/GUserAPI#GUser-getRoles?...

 

Or, you can query the sys_user_has_role table for the user and check there are no results returned (ie. there are no entries in the sys_user_has_role for the user meaning that the user has no roles).

Thanks for the response!  

 

I tried:

if ((gs.getUser().getRoles() != '')) {
answer = true;
} else {
answer = false;
}

 

Can't seem to get it to work, but going to keep trying some variations of it.  Thanks!