rokz92 rokz92 - 4 months ago 10
Python Question

custom authentication not working in django-tastypie

My question is, how do i write my own custom authentication correctly??

i have tried to follow this:
http://django-tastypie.readthedocs.org/en/latest/authentication.html#implementing-your-own-authentication-authorization

I have implemented basic method,

api.py

def prepareResponce(responceData):
"""Prepares a Json responce with status 200"""
response = JsonResponse(responceData)
return response # {"foo": "bar"}

class CustomBasicAuthentication(BasicAuthentication):
userID = None
userType = None
userAccess = None
userName = None

def is_authenticated(self, request, **kwargs):
if 'admin' in request.user.username:
return prepareResponce({'logged in': 'Admin' })
#return True
return prepareResponce({'not allowed for':userName })


def get_identifier(self, request):
return request.user.username


class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
authentication = CustomBasicAuthentication()
allowed_methods = ['get', 'post']


when i call API providing admin's username and password it's always return the else part. where am i did wrong ?

Answer

You missed return and You don't call parent is_authenticated function:

def is_authenticated(self, request, **kwargs):
    super(CustomBasicAuthentication, self).is_authenticated(request, **kwargs)
    if 'admin' == request.user.username:
         return prepareResponce({'logged in': 'Admin' })
    return prepareResponce({'not allowed for': self.userName })