Search code examples
djangotastypie

Custom Authorization class in Django Tastypie


I used the following Custom Authorization class

class CustomDjangoAuthorization(DjangoAuthorization):
    def read_detail(self, object_list, bundle):
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)
        # now we check here for specific permission
        if bundle.request.user.profile.user_status:
            raise Unauthorized("You are not allowed to access that resource.")
        return result

It gives

401 Unauthorized

when the user_status = 1. But when I change the user_status to 0, it still shows

401 Unauthorized

error.

My unsends authorizationderstanding was that for each request, tastypie checks Authorization and gives a 200 response for Ok and 401 for Unauthorized. Am I missing something here?

Hey Sean, I tried moving custom code before super. I get a

AttributeError: ‘AnonymousUser’ object has no attribute ‘profile’

Everything is working in localhost, production is giving a problem. This happens in both cases, when user_status = 1 & when user_status = 0

Using Django 1.8 and Tastypie 0.13.3.


Solution

  • Move your custom code before the call to super(), and add a check to see if the user is anonymous:

    class CustomDjangoAuthorization(DjangoAuthorization):
       def read_detail(self, object_list, bundle):
        # check here for specific permission
        if (not bundle.request.user.is_authenticated()) or bundle.request.user.profile.user_status:
            raise Unauthorized("You are not allowed to access that resource.")
        result = super(CustomDjangoAuthorization, self).read_detail(object_list, bundle)
        return result
    

    You were getting AttributeError: ‘AnonymousUser’ object has no attribute ‘profile’ because your user was logged out, so request.user was an AnonymousUser, therefore no profile.