TokenObject.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. import jwt, time, datetime
  15. OAUTH_ACCESS_TOKEN_SECRET = 'a+%zy^=@xxx%'
  16. OAUTH_REFRESH_TOKEN_SECRET = 'r+%zy^=@xaa%'
  17. OAUTH_ACCESS_TOKEN_TIME = datetime.timedelta(days=7)
  18. # refresh_token超时
  19. OAUTH_REFRESH_TOKEN_TIME = datetime.timedelta(days=30)
  20. class TokenObject:
  21. def __init__(self, token=None):
  22. self.token = token
  23. self.code = 0
  24. self.userID = None
  25. self.valid()
  26. def valid(self):
  27. try:
  28. res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256')
  29. self.userID = res.get('userID', None)
  30. except jwt.ExpiredSignatureError as e:
  31. print(repr(e))
  32. self.code = 309
  33. except Exception as e:
  34. self.code = 309
  35. else:
  36. return res
  37. def generate(self, data={}):
  38. try:
  39. access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
  40. refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
  41. now_stamp = int(time.time())
  42. access_token = jwt.encode(
  43. {'userID': data['userID'], 'exp': access_expire + now_stamp},
  44. OAUTH_ACCESS_TOKEN_SECRET,
  45. algorithm='HS256')
  46. refresh_token = jwt.encode(
  47. {'userID': data['userID'], 'exp': refresh_expire + now_stamp},
  48. OAUTH_REFRESH_TOKEN_SECRET,
  49. algorithm='HS256')
  50. res = {
  51. 'access_token': access_token.decode('utf-8'),
  52. 'access_expire': access_expire,
  53. 'refresh_expire': refresh_expire,
  54. 'refresh_token': refresh_token.decode('utf-8'),
  55. }
  56. except Exception as e:
  57. self.code = 309
  58. print(repr(e))
  59. else:
  60. return res
  61. def refresh(self):
  62. try:
  63. res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
  64. except jwt.ExpiredSignatureError as e:
  65. print('过期')
  66. print(repr(e))
  67. self.code = 309
  68. except Exception as e:
  69. self.code = 309
  70. print(repr(e))
  71. else:
  72. userID = res['userID']
  73. self.userID = userID
  74. refreshRes = self.generate(data={'userID': userID})
  75. return refreshRes
  76. # tko = TokenObject('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Inh4YXh4YSIsImV4cCI6MTU1OTYxOTczOH0.P8EIriN8KBUSUJlML6a7BmWS5TEaMyiZ6h9BVVkptZ0')
  77. # res = tko.generate(data={'id': 'xxaxxa'})
  78. # print(tko.id)