How to get a list of all roles assigned directly and indirectly (inherited) to group

List of roles assigned to group

Some time ago I needed to retrieve complete list of roles assigned to group from ServiceNow. I wanted to know which roles were granted by which group. I quickly found out that there is no easy solution for roles that are inherited from other roles. I prepared script (can be execute in Background Script or in Fix Script) which helped me to retrieve this list:

function checkIfGroupHasRoles(groupRecord){
    var grGHR = new GlideRecord('sys_group_has_role');
    grGHR.addQuery('group', groupRecord.sys_id);
    grGHR.query();
    
    return grGHR.hasNext();
}

function checkIfRoleContainsRoles (checkingRole){
    var grRC = new GlideRecord('sys_user_role_contains');
    grRC.addQuery('role.name',checkingRole);
    grRC.query();
    
    return grRC.hasNext();
}

function getArrayOfChildRoles(parentRole){
    var grRC = new GlideRecord('sys_user_role_contains');
    grRC.addQuery('role.name',parentRole);
    grRC.query();
    
    var resultArray = [];
    
    while (grRC.next()){
        var childRole = grRC.getDisplayValue('contains');
        resultArray.push(childRole.toString());

        if( checkIfRoleContainsRoles(childRole) ){
            var arrayOfChildRoles = getArrayOfChildRoles(childRole);
            resultArray = resultArray.concat(arrayOfChildRoles);
        }
    }
    return resultArray;
}

function getArrayOfAllRolesForGroup(groupRecord){
    var resultArray = [];
    
    var grGHR = new GlideRecord('sys_group_has_role');
    grGHR.addQuery('group', groupRecord.sys_id);
    grGHR.query();
    
    while(grGHR.next()){
        var role = grGHR.role.name;
        resultArray.push(role.toString());
        
        if ( checkIfRoleContainsRoles(role) ){
            var arrayOfChildRoles=[];
            arrayOfChildRoles = getArrayOfChildRoles(role);
            resultArray = resultArray.concat(arrayOfChildRoles);
        }
    }
    return resultArray;
}

function printRolesForGroups(){
    var grGR = new GlideRecord('sys_user_group');
    grGR.query();
    
    while (grGR.next()){
        if ( checkIfGroupHasRoles( grGR ) ){
            var arrayOfAllRolesForGroup = [];
            arrayOfAllRolesForGroup = getArrayOfAllRolesForGroup(grGR);
            
            var au =  new ArrayUtil();
            arrayOfAllRolesForGroup = au.unique(arrayOfAllRolesForGroup);
            
            var message  = grGR.getDisplayValue() + ': ' + arrayOfAllRolesForGroup.join(',');
            gs.print(message);
            }
        }
}
printRolesForGroups();

Leave a Reply

Your email address will not be published. Required fields are marked *