TokenObject.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: AnsjerOA
  7. @software: PyCharm
  8. @DATE: 2018/8/13 15:36
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: TokenObject.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. from Ansjer.config import OAUTH_ACCESS_TOKEN_SECRET, OAUTH_REFRESH_TOKEN_SECRET, OAUTH_ACCESS_TOKEN_TIME, \
  15. OAUTH_REFRESH_TOKEN_TIME
  16. import jwt, time
  17. from Model.models import Device_User
  18. class TokenObject:
  19. def __init__(self, token=None):
  20. if token == 'debug':
  21. token = 'x'
  22. if token == 'test':
  23. token = 'x'
  24. self.token = token
  25. self.code = 0
  26. self.lang = None
  27. self.userID = None
  28. def valid(self):
  29. try:
  30. res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256')
  31. self.userID = res.get('userID', None)
  32. self.lang = res.get('lang', None)
  33. # 刷新登录时间
  34. device_user = Device_User.objects.get(userID=self.userID)
  35. device_user.online = True
  36. device_user.save()
  37. except jwt.ExpiredSignatureError as e:
  38. print('过期')
  39. print(repr(e))
  40. # self.code = 307
  41. self.code = 309
  42. except Exception as e:
  43. # self.code = 305
  44. self.code = 309
  45. else:
  46. return res
  47. def generate(self, data={}):
  48. try:
  49. access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
  50. refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
  51. now_stamp = int(time.time())
  52. access_data = data
  53. refresh_data = data
  54. access_data['exp'] = access_expire+now_stamp
  55. refresh_data['exp'] = refresh_expire+now_stamp
  56. access_token = jwt.encode(access_data,
  57. OAUTH_ACCESS_TOKEN_SECRET,
  58. algorithm='HS256')
  59. refresh_token = jwt.encode(
  60. refresh_data,
  61. OAUTH_REFRESH_TOKEN_SECRET,
  62. algorithm='HS256')
  63. res = {
  64. 'access_token': access_token.decode('utf-8'),
  65. 'access_expire': access_expire,
  66. 'refresh_expire': refresh_expire,
  67. 'refresh_token': refresh_token.decode('utf-8'),
  68. }
  69. except Exception as e:
  70. self.code = 45
  71. print(repr(e))
  72. else:
  73. return res
  74. def refresh(self):
  75. try:
  76. res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
  77. except jwt.ExpiredSignatureError as e:
  78. print('过期')
  79. print(repr(e))
  80. self.code = 307
  81. except Exception as e:
  82. self.code = 45
  83. print(repr(e))
  84. else:
  85. userID = res['userID']
  86. lang = res['lang']
  87. refreshRes = self.generate(data={'userID': userID, 'lang': lang})
  88. return refreshRes