dataplatform/Utils/Authentication/TokenUtil.py

35 lines
949 B
Python

from typing import Union
import jwt
from datetime import datetime, timedelta
from fastapi import HTTPException
from Utils.Authentication import Config
def create_token(key: str, data: Union[str, dict], expires_delta: timedelta):
# 设置加密数据
to_encode_body = dict()
to_encode_body.update({key: data.copy()})
# 设置过期时间
expire = datetime.utcnow() + expires_delta
to_encode_body.update({"exp": expire})
# Token编码
encoded_jwt = jwt.encode(to_encode_body, Config.SECRET_KEY, algorithm=Config.ALGORITHM)
return encoded_jwt
def decode_token(token: str):
try:
payload = jwt.decode(token, Config.SECRET_KEY, algorithms=[Config.ALGORITHM])
except jwt.exceptions.ExpiredSignatureError:
raise HTTPException(status_code=201, detail="Token Has Expired")
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Invalid Token")
return payload