Skip to content

Instantly share code, notes, and snippets.

@cdcarter
Created July 1, 2020 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdcarter/9efcfacfdd72771945a4ca6b3634547f to your computer and use it in GitHub Desktop.
Save cdcarter/9efcfacfdd72771945a4ca6b3634547f to your computer and use it in GitHub Desktop.
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