jwt_token.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 explode_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. return payload
  34. '''
  35. '''
  36. def get_user(token):
  37. payload = explode_token(token)
  38. user = User.objects.get(pk=payload['uid'])
  39. return user
  40. '''
  41. '''
  42. def get_username(token):
  43. user = get_user(token)
  44. # Check if exists user
  45. if not user:
  46. return user
  47. return user.name
  48. '''
  49. '''
  50. def check_token(token):
  51. payload = explode_token(token)
  52. print(payload)
  53. user = User.objects.get(pk=payload['uid'])
  54. # Check if exists user
  55. if not user:
  56. return False
  57. return constant_time_compare(user.password, payload['password'])