Opened 6 months ago

Last modified 6 months ago

#27950 new New feature

Permission classes for Class Based Views

Reported by: Piotr Szpetkowski Owned by: nobody
Component: Generic views Version: master
Severity: Normal Keywords: permissions, view, cbv
Cc: Triage Stage: Someday/Maybe
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I would like to propose to add support for permission classes for generic views (CBV) to make it simpler to add custom requirements per specific view. Syntax could be based on what is done inside DRF at the moment, so setting it up at the view level it would be very simple and convenient:

class CustomView(View):
    permission_classes = (IsAuthenticated, IsReadOnly)

That would evaluate to IsAuthenticated AND IsReadOnly. I'm not entirely sure however what syntax should support IsAuthenticated OR IsReadOnly. One of possible ways is to write one permission class for both conditions called IsAuthenticatedOrReadOnly (it's the way DRF is doing it), however it does not sound like the best solution. I suppose that a proper (but not 100% pythonic) way to handle such cases would be to override some operators (e.g. bitwise or - that's what Q object does):

class CustomView(View):
    permission_classes = (IsAuthenticated | IsReadOnly,)

I suppose that it would be nice to be able to provide list for permission_classes as well if anyone would like to do so:

class CustomView(View):
    permission_classes = [IsAuthenticated]

In case of not meeting requirements of permission_classes it might simply return 403 Forbidden response (with a possibility to provide custom template and maybe also completely override the behavior method?)

Thanks to OOP custom permission classes might and should be very simple (just like in DRF):

class IsAuthenticated(BasePermission):
    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated

It's true that similar behavior can be achieved using decorators, however in my opinion decorator syntax is more complicated than a single class attribute. Let's keep in mind that simple is better than complex. I'd gladly start working on it if it turns out to be a good idea. In fact - I've done something alike I've described in here for one of commercial projects and it works great.

Change History (1)

comment:1 Changed 6 months ago by Tim Graham

Triage Stage: UnreviewedSomeday/Maybe

Will move to accepted if the django-developers thread yields a consensus to move forward with it.

Note: See TracTickets for help on using tickets.
Back to Top