-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokens.py
34 lines (26 loc) · 965 Bytes
/
tokens.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
26
27
28
29
30
31
32
33
34
from jose import JWTError, jwt
from datetime import datetime, timedelta
import schemas
import os
from dotenv import dotenv_values, load_dotenv
config = dotenv_values(".env")
connect = load_dotenv()
SECRET_KEY = os.getenv('SECRET_KEY')
ALGORITHM = os.getenv('ALGORITHM')
ACCESS_TOKEN_EXPIRE_MINUTES = 1
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(days=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
def verify_token(data: str, credentials_exception):
try:
payload = jwt.decode(data, SECRET_KEY, algorithms=[ALGORITHM])
user: dict = payload.get("user")
if user["username"] is None:
raise credentials_exception
token_data = schemas.TokenData(user=user)
except JWTError:
raise credentials_exception
return token_data