python - Testypie modify 401 Unauthorized response body -
i using basic authentication , default in case of wrong username , password tastypie sending 401 unauthorized response header no response body.
so how can change response body show custom error message in case of invalid authentication.
use django authentication module tastypie follow:
first import namespaces:
from django.contrib.auth import authenticate, login django.conf.urls import url tastypie.resources import modelresource tastypie.http import httpunauthorized, httpforbidden
then create class inherit 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')) # username , 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 not active.' }, httpforbidden ) else: return self.create_response(request, { 'success': false, 'message': 'username or password invalid.' }, httpunauthorized )
Comments
Post a Comment