add config.py to access configuration more easily

This commit is contained in:
maxDorninger
2025-02-23 12:49:24 +01:00
parent 58c23eb69c
commit de5047c269
4 changed files with 46 additions and 24 deletions

View File

@@ -7,6 +7,7 @@ from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from pydantic import BaseModel
import config
import database
import database.users
from database.users import UserInternal
@@ -19,14 +20,6 @@ class Token(BaseModel):
class TokenData(BaseModel):
uid: str | None = None
# to get a string like this run:
# openssl rand -hex 32
# TODO: remove secrets from files
SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
log = logging.getLogger(__name__)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/token")
@@ -42,7 +35,7 @@ async def get_current_user(token: str = Depends(oauth2_scheme)) -> UserInternal:
)
log.debug("token: " + token)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
payload = jwt.decode(token, config.auth.jwt_signing_key, algorithms=[config.auth.jwt_algorithm])
log.debug("jwt payload: " + payload.__str__())
user_uid: str = payload.get("sub")
log.debug("jwt payload sub (user uid): " + user_uid)
@@ -65,7 +58,7 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None):
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now(timezone.utc) + timedelta(minutes=config.auth.jwt_access_token_lifetime)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
encoded_jwt = jwt.encode(to_encode, config.auth.jwt_signing_key, algorithm=config.auth.jwt_algorithm)
return encoded_jwt