jwt_authentication.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. return check_token(authorization_header[prefix_length + 1:])
  24. '''
  25. '''
  26. def get_identifier(self, request):
  27. # Check content type
  28. if request.content_type != 'application/json':
  29. return False
  30. # Check authorization header
  31. if settings.JWT_ACCEPT_HEADER not in request.META:
  32. return False
  33. authorization_header = request.META.get(settings.JWT_ACCEPT_HEADER)
  34. # Check authorization header prefix
  35. if not authorization_header.startswith(settings.JWT_PREFIX_HEADER):
  36. return False
  37. prefix_length = len(settings.JWT_PREFIX_HEADER)
  38. return get_username(authorization_header[prefix_length + 1:])