#!/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 """ from Ansjer.config import OAUTH_ACCESS_TOKEN_SECRET, OAUTH_REFRESH_TOKEN_SECRET, OAUTH_ACCESS_TOKEN_TIME, \ OAUTH_REFRESH_TOKEN_TIME import jwt, time class TokenObject: def __init__(self, token=None): if token == 'debug': token = 'x' if token == 'test': token = 'x' self.token = token self.code = 0 self.lang = None self.userID = None def valid(self): try: res = jwt.decode(self.token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256') self.userID = res.get('userID', None) self.lang = res.get('lang', None) except jwt.ExpiredSignatureError as e: print('过期') print(repr(e)) self.code = 307 except Exception as e: self.code = 305 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_data = data refresh_data = data access_data['exp'] = access_expire+now_stamp refresh_data['exp'] = refresh_expire+now_stamp access_token = jwt.encode(access_data, OAUTH_ACCESS_TOKEN_SECRET, algorithm='HS256') refresh_token = jwt.encode( refresh_data, 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 = 45 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 = 307 except Exception as e: self.code = 45 print(repr(e)) else: userID = res['userID'] lang = res['lang'] refreshRes = self.generate(data={'userID': userID, 'lang': lang}) return refreshRes