user-wsc/Utils/Authentication/TokenUtil.py

34 lines
823 B
Python
Raw Normal View History

2022-11-07 13:53:42 +08:00
from typing import Union
2022-10-20 16:29:54 +08:00
import jwt
from datetime import datetime, timedelta
from Utils.Authentication import Config
2022-11-07 13:53:42 +08:00
def create_token(key: str, data: Union[str, dict], expires_delta: timedelta):
2022-11-01 01:56:57 +08:00
2022-11-07 13:53:42 +08:00
# 设置加密数据
to_encode_body = dict()
to_encode_body.update({key: data.copy()})
2022-11-01 01:56:57 +08:00
2022-10-20 16:29:54 +08:00
# 设置过期时间
2022-11-07 13:53:42 +08:00
expire = datetime.utcnow() + expires_delta
to_encode_body.update({"exp": expire})
2022-11-01 01:56:57 +08:00
2022-10-20 16:29:54 +08:00
# Token编码
2022-11-07 13:53:42 +08:00
encoded_jwt = jwt.encode(to_encode_body, Config.SECRET_KEY, algorithm=Config.ALGORITHM)
2022-11-01 14:02:58 +08:00
return encoded_jwt
2022-10-20 16:29:54 +08:00
def decode_token(token: str):
try:
payload = jwt.decode(token, Config.SECRET_KEY, algorithms=[Config.ALGORITHM])
2022-11-01 14:02:58 +08:00
except jwt.exceptions.ExpiredSignatureError:
2022-11-09 10:06:37 +08:00
return "Expired"
2022-11-07 13:53:42 +08:00
except jwt.PyJWTError:
2022-11-09 10:06:37 +08:00
return "Invalid"
2022-10-20 16:29:54 +08:00
return payload