|
|
@@ -3,6 +3,10 @@ import logging
|
|
|
from django.conf import settings
|
|
|
from django.contrib.auth.backends import ModelBackend, RemoteUserBackend as RemoteUserBackend_
|
|
|
from django.contrib.auth.models import Group, Permission
|
|
|
+from django.contrib.contenttypes.models import ContentType
|
|
|
+from django.db.models import Q
|
|
|
+
|
|
|
+from users.models import ObjectPermission
|
|
|
|
|
|
|
|
|
class ViewExemptModelBackend(ModelBackend):
|
|
|
@@ -31,6 +35,44 @@ class ViewExemptModelBackend(ModelBackend):
|
|
|
return super().has_perm(user_obj, perm, obj)
|
|
|
|
|
|
|
|
|
+class ObjectPermissionBackend(ModelBackend):
|
|
|
+ """
|
|
|
+ Evaluates permission of a user to access or modify a specific object based on the assignment of ObjectPermissions
|
|
|
+ either to the user directly or to a group of which the user is a member. Model-level permissions supersede this
|
|
|
+ check: For example, if a user has the dcim.view_site model-level permission assigned, the ViewExemptModelBackend
|
|
|
+ will grant permission before this backend is evaluated for permission to view a specific site.
|
|
|
+ """
|
|
|
+ def has_perm(self, user_obj, perm, obj=None):
|
|
|
+
|
|
|
+ # This backend only checks for permissions on specific objects
|
|
|
+ if obj is None:
|
|
|
+ return
|
|
|
+
|
|
|
+ app, codename = perm.split('.')
|
|
|
+ action, model_name = codename.split('_')
|
|
|
+ model = obj._meta.model
|
|
|
+
|
|
|
+ # Check that the requested permission applies to the specified object
|
|
|
+ if model._meta.model_name != model_name:
|
|
|
+ raise ValueError(f"Invalid permission {perm} for model {model}")
|
|
|
+
|
|
|
+ # Retrieve user's permissions for this model
|
|
|
+ # This can probably be cached
|
|
|
+ obj_permissions = ObjectPermission.objects.filter(
|
|
|
+ Q(users=user_obj) | Q(groups__user=user_obj),
|
|
|
+ model=ContentType.objects.get_for_model(obj),
|
|
|
+ **{f'can_{action}': True}
|
|
|
+ )
|
|
|
+
|
|
|
+ for perm in obj_permissions:
|
|
|
+
|
|
|
+ # Attempt to retrieve the model from the database using the
|
|
|
+ # attributes defined in the ObjectPermission. If we have a
|
|
|
+ # match, assert that the user has permission.
|
|
|
+ if model.objects.filter(pk=obj.pk, **perm.attrs).exists():
|
|
|
+ return True
|
|
|
+
|
|
|
+
|
|
|
class RemoteUserBackend(ViewExemptModelBackend, RemoteUserBackend_):
|
|
|
"""
|
|
|
Custom implementation of Django's RemoteUserBackend which provides configuration hooks for basic customization.
|