jwt_token.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.conf import settings
  4. from django.contrib.auth import authenticate
  5. from django.contrib.auth.models import User
  6. from django.utils.crypto import constant_time_compare
  7. import jwt
  8. '''
  9. '''
  10. def create_token(username, password):
  11. # Check if exists jwt key
  12. if not settings.JWT_SECRET_KEY:
  13. return None
  14. user = authenticate(username=username, password=password)
  15. # Check user authentication
  16. if not user:
  17. return user
  18. payload = {
  19. 'uid': user.id,
  20. 'password': user.password
  21. }
  22. return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm='HS256')
  23. '''
  24. '''
  25. def check_token(token):
  26. # Check if exists jwt key
  27. if not settings.JWT_SECRET_KEY:
  28. return None
  29. payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithm='HS256')
  30. # Check payload parameters
  31. if 'uid' not in payload or 'password' not in payload:
  32. return False
  33. user = User.objects.get(pk=payload['uid'])
  34. # Check if exists user
  35. if not user:
  36. return False
  37. return constant_time_compare(user.password, payload['password'])