Created
July 1, 2020 19:16
-
-
Save cdcarter/9efcfacfdd72771945a4ca6b3634547f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.backends import BaseBackend | |
from django.contrib.auth.mixins import PermissionRequiredMixin | |
from django.http.response import Http404 | |
from .models import Entry | |
class SimpleBackend(BaseBackend): | |
""" | |
Currently only works for blog.Entry, but this auth backend provides row level security for blog | |
entries and drafts. | |
list view/index/feed always uses published posts, but post detail uses non-dead posts. | |
""" | |
def has_perm(self, user_obj, perm, obj=None): | |
# not at all simple, in fact quite pathological! | |
if isinstance(obj, Entry): | |
if obj.status == 'published': | |
return True | |
if obj.status == 'draft' and (obj.public_draft or (user_obj.pk == obj.author.pk)): | |
return True | |
else: | |
return | |
class ObjectLevelPermissionRequiredMixin(PermissionRequiredMixin): | |
def get_object(self): | |
if not hasattr(self, 'object') or not self.object: | |
self.object = super().get_object() | |
return self.object | |
def has_permission(self): | |
perms = self.get_permission_required() | |
return self.request.user.has_perms(perms, self.get_object()) | |
def handle_no_permission(self): | |
raise Http404(self.get_permission_denied_message()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment