|
|
@@ -9,7 +9,9 @@ from django.core.exceptions import ImproperlyConfigured
|
|
|
from django.db.models import Q
|
|
|
|
|
|
from users.models import ObjectPermission
|
|
|
-from utilities.permissions import permission_is_exempt, resolve_permission, resolve_permission_ct
|
|
|
+from utilities.permissions import (
|
|
|
+ permission_is_exempt, qs_filter_from_constraints, resolve_permission, resolve_permission_ct,
|
|
|
+)
|
|
|
|
|
|
UserModel = get_user_model()
|
|
|
|
|
|
@@ -99,8 +101,10 @@ class ObjectPermissionMixin:
|
|
|
if not user_obj.is_active or user_obj.is_anonymous:
|
|
|
return False
|
|
|
|
|
|
+ object_permissions = self.get_all_permissions(user_obj)
|
|
|
+
|
|
|
# If no applicable ObjectPermissions have been created for this user/permission, deny permission
|
|
|
- if perm not in self.get_all_permissions(user_obj):
|
|
|
+ if perm not in object_permissions:
|
|
|
return False
|
|
|
|
|
|
# If no object has been specified, grant permission. (The presence of a permission in this set tells
|
|
|
@@ -113,21 +117,13 @@ class ObjectPermissionMixin:
|
|
|
if model._meta.label_lower != '.'.join((app_label, model_name)):
|
|
|
raise ValueError(f"Invalid permission {perm} for model {model}")
|
|
|
|
|
|
- # Compile a query filter that matches all instances of the specified model
|
|
|
- obj_perm_constraints = self.get_all_permissions(user_obj)[perm]
|
|
|
- constraints = Q()
|
|
|
- for perm_constraints in obj_perm_constraints:
|
|
|
- if perm_constraints:
|
|
|
- constraints |= Q(**perm_constraints)
|
|
|
- else:
|
|
|
- # Found ObjectPermission with null constraints; allow model-level access
|
|
|
- constraints = Q()
|
|
|
- break
|
|
|
+ # Compile a QuerySet filter that matches all instances of the specified model
|
|
|
+ qs_filter = qs_filter_from_constraints(object_permissions[perm])
|
|
|
|
|
|
# Permission to perform the requested action on the object depends on whether the specified object matches
|
|
|
# the specified constraints. Note that this check is made against the *database* record representing the object,
|
|
|
# not the instance itself.
|
|
|
- return model.objects.filter(constraints, pk=obj.pk).exists()
|
|
|
+ return model.objects.filter(qs_filter, pk=obj.pk).exists()
|
|
|
|
|
|
|
|
|
class ObjectPermissionBackend(ObjectPermissionMixin, ModelBackend):
|