[Answer]-Testypie modify 401 Unauthorized response body

1👍

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 )

Leave a comment