Check if user is part of one of multiple groups or any groups that has a group parent

samadam
Kilo Sage

I am trying to restrict record creation based on if a user is part of a group or any group that has parent as certain group. What is a good way to do this? IS it better to look at sys_grmember or sys_group and check they are part of it?

3 REPLIES 3

Deepak Negi
Mega Sage
Mega Sage

Sys_user_grmember is the table that holds the group and user relationship so thats the one you should be looking at

 

you can also use gs.getUser().isMemberOf(<group sys id>) to check if the user is member of certain group

 

you can also dot walk from the above table to check group.parent 

 

Thanks

Deepak

John Dahl
Tera Guru

To check if the user is in the given group or any of the immediate child groups, you need to do a little trickery. There is not an easy method call that I'm aware of. Dot-walking would work going UP to the parent, but not DOWN to all/any of the children.

 

Given that you have a user's sys_id and a parent group sys_id:

1. You need to get an array of all of the child group sys_ids.

2. Then you can query the sys_user_grmember table to see if the user is in any of the groups. Remember to include the parent group.

 

function isInGroups( userID, groupID ){
/* Given a User sys_id and a Group sys_id,
* Check if the user is in the group or any immediate child groups.
* Return a boolean.
*/

// Get an array of child group sys_ids.
var groupIDs = new global.GlideQuery.parse( 'sys_user_group', 'parent=' + groupID )
.select()
.reduce( function( arr, group ){
arr.push( group.sys_id );
return arr;
}, [] );

// Add the parent group ID
groupIDs.push( groupID );

// Check if the user is in any of the groups
var encodedQuery = [
'groupIN' + groupIDs.join(','),
'user=' + userID
].join('^');

var isInGroup = new global.GlideQuery.parse( 'sys_user_grmember', encodedQuery ).count() > 0;

return isInGroup;
}

 

Test Setup:

Abel Tuter is in a CHILD group and should return true for both the parent and child groups.
Beth Anglin is in a PARENT group and should return true for the parent group, but false for the child group.
System Admin (ME) is in neither group and should return false when testing either group.

Test Results:

isInGroups( AbelTuter, PARENTGROUP );     // True
isInGroups( AbelTuter, GROUP );                   // True
isInGroups( BethAnglin, PARENTGROUP );  // True
isInGroups( BethAnglin, GROUP );                 // False
isInGroups( ME, PARENTGROUP );               // False
isInGroups( ME, GROUP );                              // False

 

 

samadam
Kilo Sage

Used an encoded query on the sys_gr_member and got it working.