1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
- @AUTHOR: ASJRD018
- @NAME: AnsjerOA
- @software: PyCharm
- @DATE: 2018/8/13 15:36
- @Version: python3.6
- @MODIFY DECORD:ansjer dev
- @file: TokenObject.py
- @Contact: chanjunkai@163.com
- """
- import jwt, time, datetime
- OAUTH_ACCESS_TOKEN_SECRET = 'a+%zy^=@xxx%'
- OAUTH_REFRESH_TOKEN_SECRET = 'r+%zy^=@xaa%'
- OAUTH_ACCESS_TOKEN_TIME = datetime.timedelta(days=7)
- # refresh_token超时
- OAUTH_REFRESH_TOKEN_TIME = datetime.timedelta(days=30)
- class TokenObject:
- def __init__(self, token=None):
- self.token = token
- self.code = 0
- self.userID = None
- self.valid()
- def valid(self):
- try:
- res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256')
- self.userID = res.get('userID', None)
- except jwt.ExpiredSignatureError as e:
- print('过期')
- print(repr(e))
- self.code = 309
- except Exception as e:
- self.code = 309
- else:
- return res
- def generate(self, data={}):
- try:
- access_expire = int(OAUTH_ACCESS_TOKEN_TIME.total_seconds())
- refresh_expire = int(OAUTH_REFRESH_TOKEN_TIME.total_seconds())
- now_stamp = int(time.time())
- access_token = jwt.encode(
- {'userID': data['userID'], 'exp': access_expire + now_stamp},
- OAUTH_ACCESS_TOKEN_SECRET,
- algorithm='HS256')
- refresh_token = jwt.encode(
- {'userID': data['userID'], 'exp': refresh_expire + now_stamp},
- OAUTH_REFRESH_TOKEN_SECRET,
- algorithm='HS256')
- res = {
- 'access_token': access_token.decode('utf-8'),
- 'access_expire': access_expire,
- 'refresh_expire': refresh_expire,
- 'refresh_token': refresh_token.decode('utf-8'),
- }
- except Exception as e:
- self.code = 309
- print(repr(e))
- else:
- return res
- def refresh(self):
- try:
- res = jwt.decode(self.token, OAUTH_REFRESH_TOKEN_SECRET, algorithms='HS256')
- except jwt.ExpiredSignatureError as e:
- print('过期')
- print(repr(e))
- self.code = 309
- except Exception as e:
- self.code = 309
- print(repr(e))
- else:
- userID = res['userID']
- self.userID = userID
- refreshRes = self.generate(data={'userID': userID})
- return refreshRes
- # tko = TokenObject('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6Inh4YXh4YSIsImV4cCI6MTU1OTYxOTczOH0.P8EIriN8KBUSUJlML6a7BmWS5TEaMyiZ6h9BVVkptZ0')
- # res = tko.generate(data={'id': 'xxaxxa'})
- # print(tko.id)
|