24 lines
814 B
Python
24 lines
814 B
Python
from jwt import encode, decode, exceptions
|
|
from datetime import datetime, timedelta
|
|
from os import getenv
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
|
def expire_date(days: int):
|
|
return datetime.now() + timedelta(days)
|
|
|
|
|
|
def write_token(data: dict):
|
|
return encode(payload={**data, "exp": expire_date(2)}, key=getenv("SECRET"), algorithm="HS256")
|
|
|
|
|
|
def validate_token(token, output=False):
|
|
try:
|
|
if output:
|
|
return decode(token, key=getenv("SECRET"), algorithms=["HS256"])
|
|
decode(token, key=getenv("SECRET"), algorithms=["HS256"])
|
|
except exceptions.DecodeError:
|
|
return JSONResponse(content={"message": "Invalid Token"}, status_code=401)
|
|
except exceptions.ExpiredSignatureError:
|
|
return JSONResponse(content={"message": "Token Expired"}, status_code=401)
|