TokenObject.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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(hours=10)
  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('过期')
  32. print(repr(e))
  33. self.code = 309
  34. except Exception as e:
  35. self.code = 309
  36. else:
  37. return res
  38. def generate(self, data={}):
  39. try:
  40. access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
  41. refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
  42. now_stamp = int(time.time())
  43. access_token = jwt.encode(
  44. {'userID': data['userID'], 'exp': access_expire + now_stamp},
  45. OAUTH_ACCESS_TOKEN_SECRET,
  46. algorithm='HS256')
  47. refresh_token = jwt.encode(
  48. {'userID': data['userID'], 'exp': refresh_expire + now_stamp},
  49. OAUTH_REFRESH_TOKEN_SECRET,
  50. algorithm='HS256')
  51. res = {
  52. 'access_token': access_token.decode('utf-8'),
  53. 'access_expire': access_expire,
  54. 'refresh_expire': refresh_expire,
  55. 'refresh_token': refresh_token.decode('utf-8'),
  56. }
  57. except Exception as e:
  58. self.code = 309
  59. print(repr(e))
  60. else:
  61. return res
  62. def refresh(self):
  63. try:
  64. res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
  65. except jwt.ExpiredSignatureError as e:
  66. print('过期')
  67. print(repr(e))
  68. self.code = 309
  69. except Exception as e:
  70. self.code = 309
  71. print(repr(e))
  72. else:
  73. userID = res['userID']
  74. self.userID = userID
  75. refreshRes = self.generate(data={'userID': userID})
  76. return refreshRes
  77. # tko = TokenObject('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Inh4YXh4YSIsImV4cCI6MTU1OTYxOTczOH0.P8EIriN8KBUSUJlML6a7BmWS5TEaMyiZ6h9BVVkptZ0')
  78. # res = tko.generate(data={'id': 'xxaxxa'})
  79. # print(tko.id)