Jamie Counsell February 2016

OR style permissions for DjangoRestFramework

I'm wondering if anyone has found a good way to reverse the way permissions work in DRF (use OR instead of AND). Right now, if any of the checks fail, the request is not authenticated. I would like a way to make it so that if any of the checks pass, the request is authenticated. ie.

# currently:
permission_classes=(HasNiceHat, HasNicePants)

Request will fail for anyone with a nice hat and pants. What I would like:

# goal:
AND_permission_classes=(HasNiceHat, HasNicePants)

Will succeed if user has nice hat or nice pants.

I will assume that all users are logged in (must be for either check to pass), and that implementation of the permission is not limited in any way.

Answers


djq February 2016

Can you just create your own permission class and use that? For example:

from rest_framework import permissions

class HasNiceHatOrHasNicePants(permissions.BasePermission):
    """
    Permission to check if user has a Nice Hat or has Nice Pants.
    If both are False do not return anything.
    """
    def has_permission(self, request, view):

        if request.user.has_nicehat() or request.user.has_nicepants():
            return True

Then, import this new class into your view, and use it like this:

permission_classes = (HasNiceHatOrHasNicePants,)

It looks like rest_condition has the functionality that you need

Post Status

Asked in February 2016
Viewed 2,178 times
Voted 11
Answered 1 times

Search




Leave an answer