The CreatorCon Call for Content is officially open! Get started here.

How to check if a list of users have a role?

josh_tessaro
Giga Expert

We are on Fuji patch 3

I am trying to check if users in an OU have a role and if not add it. I have manually added the role to one user and verified the entry in the sys_user_has_role table but the below is not returning any who have the role. After running into trouble I used the solution posted here (User Has Role?) with no luck and am at my wits end.

var testou = 'sourceLIKEOU=Test Users,OU=QA,DC=domain,DC=com';

var role = 'test_user';

var gr = new GlideRecord('sys_user');

gr.addEncodedQuery(testou);

gr.query();

// I have verified that this is fetching the expected list of users who are members of the above OU

while(gr.next()){

  if(userHasRole(gr.sys_id + '', role)){   //EDIT: changed to brads recommendation below which worked

      gs.print(gr.user_name + ' has ' + role);

  }

  else

  {

      //add test_user role to user

  }      

}

// This function is taken straight from the User Has role? thread linked above

function userHasRole(userID, urole) {  

  var uhrRec = new GlideRecord('sys_user_has_role');

  uhrRec.addQuery('user', userID);

  uhrRec.addQuery('role.name', urole);

  uhrRec.query();

  return uhrRec.hasNext();

}

ideas?

Message was edited by: Josh Tessaro

1 ACCEPTED SOLUTION

Brad Tilton
ServiceNow Employee
ServiceNow Employee

Hi Josh,



I would try pushing the sys_id to a string on line 9 like the following. In a while loop the gr is actually a pointer.



if(userHasRole(gr.sys_id + '', role)){


View solution in original post

2 REPLIES 2

Brad Tilton
ServiceNow Employee
ServiceNow Employee

Hi Josh,



I would try pushing the sys_id to a string on line 9 like the following. In a while loop the gr is actually a pointer.



if(userHasRole(gr.sys_id + '', role)){


I had tried gr.sys_id but not gr.sys_id + '' which worked. Thanks!