django-role-permissions icon indicating copy to clipboard operation
django-role-permissions copied to clipboard

HasObjectPermissionMixin

Open filipeximenes opened this issue 9 years ago • 4 comments

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

filipeximenes avatar Jun 21 '16 19:06 filipeximenes

This is great, thanks.

matteing avatar Aug 25 '17 15:08 matteing

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

matteing avatar Aug 25 '17 16:08 matteing

Why this is not implemented in official release yet?

adi- avatar Aug 23 '23 08:08 adi-

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-

fjsj avatar Sep 05 '23 13:09 fjsj