2023-05-31 14:51:23 +03:00
|
|
|
import os
|
2023-05-24 23:21:22 +03:00
|
|
|
from datetime import datetime, timedelta
|
2023-05-31 14:51:23 +03:00
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from jose import jwt
|
2023-05-24 23:21:22 +03:00
|
|
|
from jose.exceptions import JWTError
|
2023-07-05 10:27:58 +03:00
|
|
|
from models.users import User
|
2023-05-24 23:21:22 +03:00
|
|
|
|
|
|
|
SECRET_KEY = os.environ.get("JWT_SECRET_KEY")
|
|
|
|
ALGORITHM = "HS256"
|
|
|
|
|
2023-07-10 15:27:49 +03:00
|
|
|
if not SECRET_KEY:
|
|
|
|
raise ValueError("JWT_SECRET_KEY environment variable not set")
|
|
|
|
|
2023-06-20 10:54:23 +03:00
|
|
|
|
2023-05-24 23:21:22 +03:00
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
|
|
|
to_encode = data.copy()
|
|
|
|
if expires_delta:
|
|
|
|
expire = datetime.utcnow() + expires_delta
|
|
|
|
else:
|
|
|
|
expire = datetime.utcnow() + timedelta(minutes=15)
|
|
|
|
to_encode.update({"exp": expire})
|
|
|
|
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
|
|
return encoded_jwt
|
|
|
|
|
2023-06-20 10:54:23 +03:00
|
|
|
|
2023-07-05 10:27:58 +03:00
|
|
|
def decode_access_token(token: str) -> User:
|
2023-05-24 23:21:22 +03:00
|
|
|
try:
|
2023-06-20 10:54:23 +03:00
|
|
|
payload = jwt.decode(
|
|
|
|
token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_aud": False}
|
|
|
|
)
|
|
|
|
except JWTError:
|
2023-07-10 15:27:49 +03:00
|
|
|
return None # pyright: ignore reportPrivateUsage=none
|
2023-06-20 10:54:23 +03:00
|
|
|
|
2023-07-10 15:27:49 +03:00
|
|
|
return User(
|
|
|
|
email=payload.get("email"),
|
|
|
|
id=payload.get("sub"), # pyright: ignore reportPrivateUsage=none
|
|
|
|
)
|
2023-07-05 10:27:58 +03:00
|
|
|
|
2023-06-20 10:54:23 +03:00
|
|
|
|
2023-06-14 22:21:13 +03:00
|
|
|
def verify_token(token: str):
|
|
|
|
payload = decode_access_token(token)
|
|
|
|
return payload is not None
|