From aca3ca9d653c54166e7c780bf5f68658a599acc2 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Fri, 7 Aug 2020 14:09:55 -0400 Subject: [PATCH] Simplify the aggregation of constraint sets --- netbox/netbox/authentication.py | 13 ++++--------- netbox/users/models.py | 8 ++++++++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/netbox/netbox/authentication.py b/netbox/netbox/authentication.py index 92127fdae..6057fc08e 100644 --- a/netbox/netbox/authentication.py +++ b/netbox/netbox/authentication.py @@ -1,4 +1,5 @@ import logging +from collections import defaultdict from django.conf import settings from django.contrib.auth.backends import ModelBackend, RemoteUserBackend as _RemoteUserBackend @@ -30,15 +31,12 @@ class ObjectPermissionBackend(ModelBackend): ).prefetch_related('object_types') # Create a dictionary mapping permissions to their constraints - perms = dict() + perms = defaultdict(list) for obj_perm in object_permissions: for object_type in obj_perm.object_types.all(): for action in obj_perm.actions: perm_name = f"{object_type.app_label}.{action}_{object_type.model}" - if perm_name in perms: - perms[perm_name].append(obj_perm.constraints) - else: - perms[perm_name] = [obj_perm.constraints] + perms[perm_name].extend(obj_perm.list_constraints()) return perms @@ -75,10 +73,7 @@ class ObjectPermissionBackend(ModelBackend): obj_perm_constraints = self.get_all_permissions(user_obj)[perm] constraints = Q() for perm_constraints in obj_perm_constraints: - if type(perm_constraints) is list: - for c in obj_perm_constraints: - constraints |= Q(**c) - elif perm_constraints: + if perm_constraints: constraints |= Q(**perm_constraints) else: # Found ObjectPermission with null constraints; allow model-level access diff --git a/netbox/users/models.py b/netbox/users/models.py index 6edbd9352..b25a75134 100644 --- a/netbox/users/models.py +++ b/netbox/users/models.py @@ -285,3 +285,11 @@ class ObjectPermission(models.Model): def __str__(self): return self.name + + def list_constraints(self): + """ + Return all constraint sets as a list (even if only a single set is defined). + """ + if type(self.constraints) is not list: + return [self.constraints] + return self.constraints