TokenObject.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. class TokenObject:
  18. def __init__(self, token=None):
  19. if token == 'debug':
  20. token = 'x'
  21. if token == 'test':
  22. token = 'x'
  23. self.token = token
  24. self.code = 0
  25. self.lang = None
  26. self.userID = None
  27. def valid(self):
  28. try:
  29. res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256')
  30. self.userID = res.get('userID', None)
  31. self.lang = res.get('lang', None)
  32. except jwt.ExpiredSignatureError as e:
  33. print('过期')
  34. print(repr(e))
  35. self.code = 307
  36. except Exception as e:
  37. self.code = 305
  38. else:
  39. return res
  40. def generate(self, data={}):
  41. try:
  42. access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
  43. refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
  44. now_stamp = int(time.time())
  45. access_data = data
  46. refresh_data = data
  47. access_data['exp'] = access_expire+now_stamp
  48. refresh_data['exp'] = refresh_expire+now_stamp
  49. access_token = jwt.encode(access_data,
  50. OAUTH_ACCESS_TOKEN_SECRET,
  51. algorithm='HS256')
  52. refresh_token = jwt.encode(
  53. refresh_data,
  54. OAUTH_REFRESH_TOKEN_SECRET,
  55. algorithm='HS256')
  56. res = {
  57. 'access_token': str(access_token),
  58. 'access_expire': access_expire,
  59. 'refresh_expire': refresh_expire,
  60. 'refresh_token': str(refresh_token),
  61. }
  62. except Exception as e:
  63. self.code = 45
  64. print(repr(e))
  65. else:
  66. return res
  67. def refresh(self):
  68. try:
  69. res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
  70. except jwt.ExpiredSignatureError as e:
  71. print('过期')
  72. print(repr(e))
  73. self.code = 307
  74. except Exception as e:
  75. self.code = 45
  76. print(repr(e))
  77. else:
  78. userID = res['userID']
  79. lang = res['lang']
  80. refreshRes = self.generate(data={'userID': userID, 'lang': lang})
  81. return refreshRes