JWTAuthentication_diy.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from rest_framework_jwt.serializers import jwt_encode_handler, jwt_decode_handler
  2. from rest_framework.authentication import BaseAuthentication
  3. from rest_framework.exceptions import AuthenticationFailed
  4. import jwt
  5. from .AESencipher import aescrypt
  6. from .db_utils import MySQLTool
  7. from bigdataAPI.settings import SECRET_KEY
  8. from django.core.cache import cache as default_cache
  9. PrAes = aescrypt(SECRET_KEY, 'ECB', '', 'gbk')
  10. def get_token(user):
  11. data = str(user.id) + "," + user.username + "," + str(user.user_modules)
  12. data = PrAes.aesencrypt(data)
  13. payload = {"token": data}
  14. token = jwt_encode_handler(payload)
  15. return token
  16. class MyJWTAuthentication(BaseAuthentication):
  17. def authenticate(self, request):
  18. token = request.META.get('HTTP_AUTHORIZATION')
  19. if token:
  20. try:
  21. payload = jwt_decode_handler(token)
  22. data = payload["token"]
  23. if '%2B' in data or " " in data:
  24. data = str(data).replace("%2B", "+").replace(" ", "+")
  25. data = PrAes.aesdecrypt(data)
  26. data_list = data.split(",")
  27. user = {"uid": data_list[0], "username": data_list[1], "user_modules": data_list[2]}
  28. return (user, token)
  29. except jwt.ExpiredSignature:
  30. msg = 'token过期'
  31. raise AuthenticationFailed(msg)
  32. except jwt.DecodeError:
  33. msg = 'toke非法'
  34. raise AuthenticationFailed(msg)
  35. except jwt.InvalidTokenError:
  36. msg = '用户非法'
  37. raise AuthenticationFailed(msg)
  38. except Exception as e:
  39. msg = str(e)
  40. raise AuthenticationFailed(msg)
  41. raise AuthenticationFailed('token为空')
  42. def API_get_uid(token):
  43. sql = f"select uid from sa_device_user where api_token='{token}';"
  44. m = MySQLTool()
  45. result = m.execute_by_one(sql)
  46. if result:
  47. uid = result['uid']
  48. else:
  49. uid = ""
  50. return uid
  51. class APIAuthentication(BaseAuthentication):
  52. cache = default_cache
  53. def authenticate(self, request):
  54. token = request.META.get('HTTP_AUTHORIZATION')
  55. if token:
  56. # uid_sql = 896
  57. uid_cache = self.cache.get(token)
  58. if uid_cache:
  59. return (uid_cache,token)
  60. uid_sql = API_get_uid(token)
  61. if uid_sql:
  62. self.cache.set(token,uid_sql,60*1)
  63. return (uid_sql,token)
  64. raise AuthenticationFailed("校验失败")
  65. raise AuthenticationFailed('Authorization为空')