#!/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 from Model.models import Device_User class TokenObject: def __init__(self, token=None): if token == 'local': token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTQzOTA5MDUwNDEzMTM4MDAxMzgwMDAiLCJsYW5nIjoiZW4iLCJ1c2VybmFtZSI6IjEzODAwMTM4MDAxIiwiZXhwIjoxNTQ3NjA4NDg0fQ.i-zPz6fCXJKws3o3cETYms0Sgw3fkdfe8HuB-929AyY' if token == 'test': token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySUQiOiIxNTE1NjQyNjIzMzc5Mzk1MTM4MDAxMzgwMDEiLCJsYW5nIjoiZW4iLCJleHAiOjE1NDcwMTMzMjV9.4Q-hqqihFClYKCIoUd16ZZe2FRvpElmio6P25Qpg26Q' self.token = token self.lang = None self.userID = None self.user = '' self.valid() if token is None: self.code = 309 else: self.code = 0 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) self.user = res.get('user', '') # 刷新登录时间 device_user = Device_User.objects.get(userID=self.userID) device_user.online = True device_user.save() except jwt.ExpiredSignatureError as e: print('过期') print(repr(e)) self.code = 309 except Exception as e: self.code = 309 else: self.code = 0 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 = 309 print(repr(e)) else: self.code = 0 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: self.code = 0 userID = res.get('userID','') lang = res.get('lang','') user = res.get('user','') refreshRes = self.generate(data={'userID': userID, 'lang': lang,'user':user}) return refreshRes