You are currently viewing g_user.hasRole() vs g_user.hasRoleExactly() in ServiceNow?

g_user.hasRole() vs g_user.hasRoleExactly() in ServiceNow?

Developers are confused between hasRole() and hasRoleExactly(). In this article, I am showing live examples of both of these functions. it is gonna be fun … stay tuned.

Test both function as admin in client script

Below is the example when i logged in as an admin. Here itil, sn_cmdb_editor are in sys_user_has_role table for this user.

//Client Script Code
alert(g_user.hasRole('itil') + "-" + g_user.hasRole('sn_cmdb_editor') + "-" + g_user.hasRole('snc_internal'));
alert(g_user.hasRoleExactly('itil') + "-" + g_user.hasRoleExactly('sn_cmdb_editor') + "-" + g_user.hasRoleExactly('snc_internal'));

//Solution
First Alert -> true-true-true
2nd Alert -> true-true-false
  • No matter which role you enter if the logged in user is admin, hasRole() always return true
  • Whereas hasRoleExactly() return true if and only if the role is present in sys_user_has_role table for that user

Test both functions again with admin but change in roles

Now, I replace sn_cmdb_editor role with itil_admin role, which is not in sys_user_has_role table for this admin user

//Client Script Code
alert(g_user.hasRole('itil') + "-" + g_user.hasRole('itil_admin') + "-" + g_user.hasRole('snc_internal'));
alert(g_user.hasRoleExactly('itil') + "-" + g_user.hasRoleExactly('itil_admin') + "-" + g_user.hasRoleExactly('snc_internal'));
//Solution
First Alert -> true-true-true
2nd Alert -> true-false-false
  • This time again hasRole() returned true for all three statements
  • However, hasRoleExactly() returned false for itil_admin & snc_internal which are not in the table sys_user_has_role table for loggedin admin user.

Test both functions as non-admin in client script

This time we try executing functions as non admin. Here itil is present in sys_user_has_role and action_designer is not present.

//Client Script Code
alert(g_user.hasRole('itil') + "-" + g_user.hasRole('action_designer') + "-" + g_user.hasRole('snc_internal'));
alert(g_user.hasRoleExactly('itil') + "-" + g_user.hasRoleExactly('action_designer') + "-" + g_user.hasRoleExactly('snc_internal'));

//Solution
First Alert -> true-false-false
2nd Alert -> true-false-false
  • this time both the functions are returning same result.
  • It means both functions differs only in case of admin as depicted above cases.

Testing with wrong role name “opsingh”

//Client Script Code
alert(g_user.hasRole('itil') + "-" + g_user.hasRole('cmdb_query_builder') + "-" + g_user.hasRole('opsingh'));
alert(g_user.hasRoleExactly('itil') + "-" + g_user.hasRoleExactly('cmdb_query_builder') + "-" + g_user.hasRoleExactly('opsingh'));

//Solution as admin
First Alert -> true-true-true
2nd Alert -> true-true-false
//Solution as non-admin
First Alert -> true-true-false
2nd Alert -> true-true-false

Leave a Reply