jwt_token.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. from jwt import DecodeError
  8. import jwt
  9. '''
  10. '''
  11. def create_token(username, password):
  12. # Check if exists jwt key
  13. if not settings.JWT_SECRET_KEY:
  14. return None
  15. user = authenticate(username=username, password=password)
  16. # Check user authentication
  17. if not user:
  18. return user
  19. payload = {
  20. 'uid': user.id,
  21. 'password': user.password
  22. }
  23. return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm='HS256')
  24. '''
  25. '''
  26. def explode_token(token):
  27. # Check if exists jwt key
  28. if not settings.JWT_SECRET_KEY:
  29. return None
  30. payload = None
  31. try:
  32. payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithm='HS256')
  33. except DecodeError:
  34. return False
  35. # Check payload parameters
  36. if 'uid' not in payload or 'password' not in payload:
  37. return False
  38. return payload
  39. '''
  40. '''
  41. def get_user(token):
  42. payload = explode_token(token)
  43. user = User.objects.get(pk=payload['uid'])
  44. return user
  45. '''
  46. '''
  47. def get_username(token):
  48. user = get_user(token)
  49. # Check if exists user
  50. if not user:
  51. return user
  52. return user.name
  53. '''
  54. '''
  55. def check_token(token):
  56. payload = explode_token(token)
  57. if not payload:
  58. return False
  59. print(payload['uid'])
  60. user = User.objects.get(pk=payload['uid'])
  61. # Check if exists user
  62. if not user:
  63. return False
  64. return constant_time_compare(user.password, payload['password'])