Break/Fix : User's group roles

Mimi Edet
Tera Guru

I need help with  a script that that will go through the members of a given group or list of groups and compare the user's roles to the group's roles.

If the user does not have all the roles given by the group, the script should remove and re-add them to the group

1 REPLY 1

Eshwar Reddy
Kilo Sage

Hi @Mimi Edet 

Use Below script

// Function to compare user roles with group roles and update memberships
function updateUserGroupRoles(userSysId, groupSysId) {
var userGr = new GlideRecord('sys_user');
if (userGr.get(userSysId)) {
// Get user roles
var userRoles = getUserRoles(userGr);

var groupGr = new GlideRecord('sys_user_group');
if (groupGr.get(groupSysId)) {
// Get group roles
var groupRoles = getGroupRoles(groupGr);

// Check if user has all group roles
if (!hasAllRoles(userRoles, groupRoles)) {
// Remove user from group
removeUserFromGroup(userSysId, groupSysId);
// Re-add user to group
addUserToGroup(userSysId, groupSysId);
}
}
}
}

// Function to get user roles
function getUserRoles(userGr) {
var roles = [];
var roleGr = new GlideRecord('sys_user_has_role');
roleGr.addQuery('user', userGr.sys_id);
roleGr.query();
while (roleGr.next()) {
roles.push(roleGr.role.sys_id);
}
return roles;
}

// Function to get group roles
function getGroupRoles(groupGr) {
var roles = [];
var roleGr = new GlideRecord('sys_group_has_role');
roleGr.addQuery('group', groupGr.sys_id);
roleGr.query();
while (roleGr.next()) {
roles.push(roleGr.role.sys_id);
}
return roles;
}

// Function to check if user has all required roles
function hasAllRoles(userRoles, groupRoles) {
for (var i = 0; i < groupRoles.length; i++) {
if (userRoles.indexOf(groupRoles[i]) === -1) {
return false;
}
}
return true;
}

// Function to remove user from group
function removeUserFromGroup(userSysId, groupSysId) {
var groupUserGr = new GlideRecord('sys_user_grmember');
groupUserGr.addQuery('user', userSysId);
groupUserGr.addQuery('group', groupSysId);
groupUserGr.query();
if (groupUserGr.next()) {
groupUserGr.deleteRecord();
}
}

// Function to add user to group
function addUserToGroup(userSysId, groupSysId) {
var groupUserGr = new GlideRecord('sys_user_grmember');
groupUserGr.initialize();
groupUserGr.user = userSysId;
groupUserGr.group = groupSysId;
groupUserGr.insert();
}

// Example usage
var userSysId = 'user_sys_id_here'; // Replace with the actual user Sys ID
var groupSysId = 'group_sys_id_here'; // Replace with the actual group Sys ID
updateUserGroupRoles(userSysId, groupSysId);


Please mark this response as Correct and Helpful if it helps you can mark more that one reply as accepted solution


Thanks
Esh