Script to Check if User is in one of the Admin Groups or Has Admin role

saggi
Tera Contributor

Hi All,

I am trying to write a code in a script include to check whether user has a admin role or isMember of one of the admin Group.

This is not working

Below is the script I have written so far.

/////////////////////////// to check if user has admin role or not

var userID = this.getParameter('sysparm_userID');
var gaAdmin = new GlideRecord('sys_user_has_role');
gaAdmin.addEncodedQuery('role.name=security_admin^ORrole.name=admin^user.sys_id='+userID);
gaAdmin.query();
if (gaAdmin.next()) {
return true;
}
else {
return false;
}

///////////////////////////// to check if user is in Admin group

var grpsArray = [];
var gr = new GlideRecord('sys_group_has_role');
gr.addEncodedQuery('role.name=admin^ORrole.name=security_admin');

gr.query();
while (gr.next()) {
grpsArray.push(gr.group.toString());
}
// return grpsArray;

for(var y=0; y < grpsArray.length; y++){


var isMember = gs.getUser().getUserByID('userID').isMemberOf(grpsArray[y]);

if (isMember)
{ return true;
break;
}

 

14 REPLIES 14

saggi
Tera Contributor

Hi Mark,

I can't use g_user since I don't need the logged in user .I need the user whose sys_user record is open

The script which I have shared above will serve your purpose.

If a user is provided a role directly, the inherited field is false on sys_user_has_role table.

However, if the user gets a role from group, the inherited field is true on sys_user_has_role table.

My script is written in such a way that it will return you the value accordingly.

Mark Roethof
Tera Patron
Tera Patron

I simplified your code. See below. Is tested, works fine.

Business Rule
Table: <your table>
When: Display
Condition: gs.hasRole('admin') || gs.isMemberOf('<your group name>')
Script:

(function executeRule(current, previous /*null when async*/) {

	g_scratchpad.admin = true;

})(current, previous);


Client Script
Table: <your table>
Type: onLoad
Script: 

function onLoad() {
   
	if(g_scratchpad.admin) {
		g_form.addWarningMessage('You are and admin!');
	}
   
}


If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020, 2021 ServiceNow Community MVP
2020, 2021 ServiceNow Developer MVP

---

LinkedIn
Community article, blog, video list

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Hi @Mark Roethof ,

But the point is that @saggi need to show different messages if the user belong to admin group and if the user has admin role.

Moreover, your business rule will only check for logged in user which is not the use case.

 

Regards,

Mahesh Kumar

Yes I have to do it from a script include only ,Wont be able to use Buisness rule.

Also the custom code will remove roles from sys_user_has_role table for the user ,however user is in the group.