jwt_authentication.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from tastypie.authentication import Authentication
  4. from django.contrib.auth.models import User
  5. from django.conf import settings
  6. from api.utils.jwt_token import check_token, get_username
  7. import simplejson as json
  8. class JWTAuthentication(Authentication):
  9. '''
  10. '''
  11. def is_authenticated(self, request, **kwargs):
  12. # # Check content type
  13. # if request.content_type != 'application/json':
  14. # return False
  15. # Check authorization header
  16. if settings.JWT_ACCEPT_HEADER not in request.META:
  17. return False
  18. authorization_header = request.META.get(settings.JWT_ACCEPT_HEADER)
  19. # Check authorization header prefix
  20. if not authorization_header.startswith(settings.JWT_PREFIX_HEADER):
  21. return False
  22. prefix_length = len(settings.JWT_PREFIX_HEADER)
  23. (_, ok) = check_token(authorization_header[prefix_length + 1:])
  24. return ok
  25. '''
  26. '''
  27. def get_identifier(self, request):
  28. # Check content type
  29. if request.content_type != 'application/json':
  30. return False
  31. # Check authorization header
  32. if settings.JWT_ACCEPT_HEADER not in request.META:
  33. return False
  34. authorization_header = request.META.get(settings.JWT_ACCEPT_HEADER)
  35. # Check authorization header prefix
  36. if not authorization_header.startswith(settings.JWT_PREFIX_HEADER):
  37. return False
  38. prefix_length = len(settings.JWT_PREFIX_HEADER)
  39. return get_username(authorization_header[prefix_length + 1:])