-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions_jwt.py
25 lines (21 loc) · 884 Bytes
/
functions_jwt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from jwt import encode, decode
from jwt import exceptions
from datetime import datetime, timedelta
from os import getenv
from fastapi.responses import JSONResponse
def expire_date(days: int):
date = datetime.now()
new_date = date + timedelta(days)
return new_date
def write_token(data: dict):
token = encode(payload={**data, "exp": expire_date(2) }, key=getenv("SECRET"), algorithm="HS256")
return token
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={"detail": "Invalid Token"}, status_code=401)
except exceptions.ExpiredSignatureError:
return JSONResponse(content={"detail": "Token Expired"}, status_code=401)