g_user.hasRole is returning false if users have snc_external roles

kemmy1
Tera Guru

We just checked this KB and found this article that confirms this.  g_user.hasRole is returning false if users have external roles - Support and Troubleshooting

 

So the question is, how do you check roles on a client script?

2 REPLIES 2

lauri457
Giga Sage

Just call the method with the second parameter as true. GlideUser | ServiceNow Developers

g_user.hasRole("snc_external", true);

It's not stated in the documentation but if you pass a truthy value then the role is checked against g_user.allRoles and not g_user.roles. For some reason roles gets set with an empty value but allRoles has all the roles + snc_internal/external

    hasRole: function(role, includeDefaults) {
       if (this.hasRoleExactly('maint', includeDefaults))
           return true;
       if (this.hasRoleExactly(role, includeDefaults))
           return true;
       if (role == 'maint')
           return false;
       if (this.hasRoleExactly('admin', includeDefaults))
           return true;
       return false;
    },
	//
    hasRoleExactly: function(role, includeDefaults) {
    	if (!role || typeof role != 'string')
    		return false;
    	
    	var rolesToCheck = this.roles;
    	if (includeDefaults)  // should end up here
    		rolesToCheck = this.allRoles;  
    	for (var x = 0, l = rolesToCheck.length; x < l; x++) {
            if (rolesToCheck[x].toLowerCase() == role.toLowerCase())
                return true;
        }
        return false;
    },



kaushal_snow
Giga Sage

@kemmy1 ,

 

g_user.hasRole() and g_user.hasRoles() will return false for users who only have snc_external (or snc_internal) because those explicit roles are treated specially and not counted as real roles by the client api......so to check roles reliably in a client script you either rely on g_user.hasRole('role_name') for normal roles, use g_user.hasRoleExactly() when you need exact matching........or do a server side check with GlideAjax (e.g......... through a script include that runs gs.getUser().hasRole() or checks the user roles via sys_user_has_role) and then return the result back to the client.......because the client api doesn’t expose all roles..........

 

If you found my response helpful, please mark it as ‘Accept as Solution’ and ‘Helpful’. This helps other community members find the right answer more easily and supports the community.

 

Thanks and Regards,
Kaushal Kumar Jha - ServiceNow Technical Consultant - Rising Star/Class of Legends 2025