django-role-permissions
django-role-permissions copied to clipboard
HasObjectPermissionMixin
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied
from django.conf import settings
from rolepermissions.verifications import has_object_permission
class HasObjectPermissionMixin(object):
checker_name = ''
def dispatch(self, request, *args, **kwargs):
user = request.user
if user.is_authenticated():
self.object = self.get_object()
if has_object_permission(self.checker_name, request.user, self.object):
return super().dispatch(request, *args, **kwargs)
if hasattr(settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN'):
return redirect_to_login(request.get_full_path())
raise PermissionDenied
This is great, thanks.
I made a few modifications to allow use of messaging framework, and allow guests if an object is published for example. Hope it's of use to someone:
class HasObjectPermissionMixin(object):
checker_name = ''
checker_allow_guests = False
checker_denied_message = None
def dispatch(self, request, *args, **kwargs):
user = request.user
if user.is_authenticated() or self.checker_allow_guests:
self.object = self.get_object()
if has_object_permission(self.checker_name, request.user, self.object):
return super().dispatch(request, *args, **kwargs)
if hasattr(settings, 'ROLEPERMISSIONS_REDIRECT_TO_LOGIN'):
if self.checker_denied_message:
messages.add_message(request, messages.INFO,
self.checker_denied_message)
return redirect_to_login(request.get_full_path())
raise PermissionDenied
Why this is not implemented in official release yet?
Because there are no developers with enough free time to implement this, test this, and ensure it has a good API. Feel free to open a PR, though. @adi-