r.bhardwaj
r.bhardwaj

Reputation: 1613

Testypie modify 401 Unauthorized response body

I am using Basic Authentication and by default in case of wrong username and password tastypie is sending 401 Unauthorized response header with no response body.

So how can we change the response body to show custom error message in case of invalid authentication.

Upvotes: 0

Views: 270

Answers (1)

Aida.Mirabadi
Aida.Mirabadi

Reputation: 1046

Use django authentication module for Tastypie As follow:

First Import NameSpaces:

from django.contrib.auth import authenticate, login
from django.conf.urls import url
from tastypie.resources import ModelResource
from tastypie.http import HttpUnauthorized, HttpForbidden

Then create your class inherit from ModelResource:

class UserResource(ModelResource):
    class Meta:
        fields = ['username', 'password']
        allowed_methods = ['post']
        resource_name = 'user'
        include_resource_uri = False

    def override_urls(self):
       return [
           url(r"^(?P<resource_name>%s)/login%s$" %
               (self._meta.resource_name, trailing_slash()),
               self.wrap_view('login'), name="api_login"),]

    def login(self, request, **kwargs):
       self.method_check(request, allowed=['post'])
       data = self.deserialize(request,
                               request.body,
                               format=request.META.get('CONTENT_TYPE',
                                                    'application/json'))

       # Get Username and Password.
       username = data.get('username', '')
       password = data.get('password', '')

      user = authenticate(username=username, password=password)
      if user:
         if user.is_active:
            login(request, user)
            return self.create_response(request, {
              'success': True
            })
         else:
            return self.create_response(request, {
              'success': False,
              'message': 'User is not active.'               
            }, HttpForbidden )
      else:
         return self.create_response(request, {
           'success': False,
           'message': 'Username or Password is Invalid.'
         }, HttpUnauthorized )

Upvotes: 1

Related Questions