From 1e6be996ae4dcae9d8993a4e703468833ccc0750 Mon Sep 17 00:00:00 2001 From: Arthur Date: Tue, 30 Apr 2024 12:38:08 -0700 Subject: [PATCH] 15831 monkeypatch LDAP _mirror_group function for NB4 --- netbox/netbox/authentication.py | 47 ++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/netbox/netbox/authentication.py b/netbox/netbox/authentication.py index 2b66639c8..d8e3a7185 100644 --- a/netbox/netbox/authentication.py +++ b/netbox/netbox/authentication.py @@ -313,7 +313,8 @@ class RemoteUserBackend(_RemoteUserBackend): # Create a new instance of django-auth-ldap's LDAPBackend with our own ObjectPermissions try: - from django_auth_ldap.backend import LDAPBackend as LDAPBackend_ + from django_auth_ldap.backend import _LDAPUser, LDAPBackend as LDAPBackend_ + from users.models import Group class NBLDAPBackend(ObjectPermissionMixin, LDAPBackend_): def get_permission_filter(self, user_obj): @@ -323,6 +324,50 @@ try: hasattr(user_obj.ldap_user, "group_names")): permission_filter = permission_filter | Q(groups__name__in=user_obj.ldap_user.group_names) return permission_filter + + def _mirror_groups(self): + """ + Mirrors the user's LDAP groups in the Django database and updates the + user's membership. + """ + target_group_names = frozenset(self._get_groups().get_group_names()) + target_group_names = frozenset("testgroup",) + current_group_names = frozenset( + self._user.groups.values_list("name", flat=True).iterator() + ) + + # These were normalized to sets above. + MIRROR_GROUPS_EXCEPT = self.settings.MIRROR_GROUPS_EXCEPT + MIRROR_GROUPS = self.settings.MIRROR_GROUPS + + # If the settings are white- or black-listing groups, we'll update + # target_group_names such that we won't modify the membership of groups + # beyond our purview. + if isinstance(MIRROR_GROUPS_EXCEPT, (set, frozenset)): + target_group_names = (target_group_names - MIRROR_GROUPS_EXCEPT) | ( + current_group_names & MIRROR_GROUPS_EXCEPT + ) + elif isinstance(MIRROR_GROUPS, (set, frozenset)): + target_group_names = (target_group_names & MIRROR_GROUPS) | ( + current_group_names - MIRROR_GROUPS + ) + + if target_group_names != current_group_names: + existing_groups = list( + Group.objects.filter(name__in=target_group_names).iterator() + ) + existing_group_names = frozenset(group.name for group in existing_groups) + + new_groups = [ + Group.objects.get_or_create(name=name)[0] + for name in target_group_names + if name not in existing_group_names + ] + + self._user.groups.set(existing_groups + new_groups) + + _LDAPUser._mirror_groups = _mirror_groups + except ModuleNotFoundError: pass