quivr/backend/auth/jwt_token_handler.py
MaHDi 8af6d61e76
improve (importing): reorganization of the import structure (#964)
* reorganize import level

* add __init__, reorganize import from __init__

* reorganize import level

* reorganize import level

* fix circular import error by keep the import deep as "from models.settings"

* fix the relative import

* restor unwanted staged files

* add backend/venv and backend/.env to gitignore

* clean importing
2023-08-21 12:25:16 +02:00

44 lines
1.2 KiB
Python

import os
from datetime import datetime, timedelta
from typing import Optional
from jose import jwt
from jose.exceptions import JWTError
from models import User
SECRET_KEY = os.environ.get("JWT_SECRET_KEY")
ALGORITHM = "HS256"
if not SECRET_KEY:
raise ValueError("JWT_SECRET_KEY environment variable not set")
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
def decode_access_token(token: str) -> User:
try:
payload = jwt.decode(
token, SECRET_KEY, algorithms=[ALGORITHM], options={"verify_aud": False}
)
except JWTError:
return None # pyright: ignore reportPrivateUsage=none
return User(
email=payload.get("email"),
id=payload.get("sub"), # pyright: ignore reportPrivateUsage=none
)
def verify_token(token: str):
payload = decode_access_token(token)
return payload is not None