Script to Check if User is in one of the Admin Groups or Has Admin role
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-30-2021 09:19 PM
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;
}
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-30-2021 09:38 PM
Hi,
Can you check if the grpsArray returns any value.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-30-2021 09:46 PM
Yes It can Return Values and even group name
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-30-2021 09:52 PM
I want the below code to return true at the end as soon as true value is generation while going through the for loop .
for(var y=0; y < grpsArray.length; y++){
var isMember = gs.getUser().getUserByID('userID').isMemberOf(grpsArray[y]);
if (isMember)
{ return true;
break;
}

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-30-2021 09:57 PM
You do not need these many complex functions.
Eventually if the user is a part of a group which contains admin role then user will also have admin role.
Use this simple script to return true or false if the user has admin role or not:
var userID = this.getParameter('sysparm_userID');
var now_GR = new GlideRecord("sys_user");
now_GR.addQuery('sys_id', userID);
now_GR.query();
if (now_GR.next()) {
if (now_GR.accumulated_roles.toString().indexOf(",admin,") != -1) {
return true;
}
}
return false;