34 lines
823 B
Python
34 lines
823 B
Python
from typing import Union
|
|
|
|
import jwt
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
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:
|
|
return "Expired"
|
|
except jwt.PyJWTError:
|
|
return "Invalid"
|
|
return payload
|