quantitative_factor_evaluation/src/utils/token.py

61 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#coding=utf-8
from ast import If
from typing import Any
import jwt
from jwt.exceptions import InvalidTokenError
from passlib.context import CryptContext
from datetime import datetime, timedelta,timezone
from src.utils.config import read_config
# 密钥用于签名和验证JWT
SECRET_KEY = 'fastapi_longyu12'
# 令牌过期时间 默认十天
EXP = datetime.now(timezone.utc)+timedelta(days=1)
project = read_config("project")
if project.get("tokenTIme"):
EXP = datetime.now(timezone.utc)+ timedelta(days=project.get("tokenTIme"))
"""
生成 token 令牌
@payload: Any 存在token里面的信息
"""
def createToken(payload: Any):
payload["exp"] = EXP
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256' )
return token
def vertify_is_login(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"], verify=False)
print(int(payload.get("exp")) , int((datetime.now(timezone.utc)).timestamp()))
if int(payload.get("exp")) < int((datetime.now(timezone.utc)).timestamp()):
print("登录已过期")
return False
else:
return True
except jwt.exceptions.ExpiredSignatureError:
print("登录已过期")
return False
except (jwt.exceptions.InvalidSignatureError, jwt.exceptions.DecodeError):
print("无效凭证")
return False
# def getTokenInfo():
# 载荷即JWT中包含的信息
# payload = {
# 'user_id': 123,
# 'username': 'john_doe',
# 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1)
# }
# # 生成JWT
# token = jwt.encode(payload, secret_key, algorithm='HS256')
# print('Generated JWT:', token)