private void processGroups()

in saml-authentication-server/src/main/java/jetbrains/buildServer/auth/saml/plugin/SamlAuthenticationScheme.java [273:325]


    private void processGroups(@NotNull SUser user, String groups, boolean removeUnassignedGroups) {
        if (groups == null) groups = "";

        // Get a Map of TeamCity groups, keyed by lowercase group Key
        var teamcityGroups = userGroupManager.getUserGroups().stream()
                .collect(Collectors.toMap(g -> g.getKey().toLowerCase(),
                        Function.identity()));

        // Get a lower-cased list of users current groups
        List<String> usersCurrentGroups = user.getUserGroups().stream()
                .filter(g -> !g.getKey().equals("ALL_USERS_GROUP")) // We don't want to remove the 'ALL_USERS_GROUP'
                .map(g -> g.getKey().toLowerCase())
                .collect(Collectors.toList());
        LOG.debug(String.format("Users current groups = '%s'", usersCurrentGroups));

        // Split the 'groups' string, lowercase and trim empty results
        List<String> usersAssignedGroups = Arrays.stream(groups.split(", "))
                .map(String::trim)
                .map(String::toLowerCase)
                .filter(StringUtil::isNotEmpty)
                .map(s -> "mlad bla-bla-bla".equals(s) ? "maplarge_admins" : s)
                .map(s -> "mlad bla-bla-bla another".equals(s) ? "maplarge_devs" : s)
                .collect(Collectors.toList());
        LOG.debug(String.format("Users assigned groups from SAML response: '%s'", usersAssignedGroups));

        // What groups to add and what groups to remove
        List<String> groupsToAdd = new ArrayList<>(CollectionUtils.subtract(usersAssignedGroups, usersCurrentGroups));

        // Add any new groups
        groupsToAdd.forEach(addGroup -> {
           if (teamcityGroups.containsKey(addGroup)) {
               LOG.info(String.format("Adding user to group '%s'", addGroup));
               teamcityGroups.get(addGroup).addUser(user);
           } else {
               LOG.info(String.format("No matching TeamCity group found for '%s'", addGroup));
           }
        });

        // Optionally remove groups that are no longer assigned in SAML response.
        if (removeUnassignedGroups) {
            List<String> groupsToRemove = new ArrayList<>(CollectionUtils.subtract(usersCurrentGroups, usersAssignedGroups));

            // Remove any groups that are no longer mapped
            groupsToRemove.forEach(removeGroup -> {
                if (teamcityGroups.containsKey(removeGroup)) {
                    LOG.info(String.format("Group '%s' has been unassigned from user. Removing...", removeGroup));
                    teamcityGroups.get(removeGroup).removeUser(user);
                } else {
                    LOG.warn(String.format("Existing mapped TeamCity group not found to remove: '%s'", removeGroup));
                }
            });
        }
    }