diff --git a/app/dependencies.py b/app/dependencies.py index 9c28232c..01cdcf56 100644 --- a/app/dependencies.py +++ b/app/dependencies.py @@ -17,6 +17,7 @@ templates = Jinja2Templates(directory=TEMPLATES_PATH) templates.env.add_extension("jinja2.ext.i18n") + # Configure logger logger = LoggerCustomizer.make_logger( config.LOG_PATH, diff --git a/app/internal/security/dependencies.py b/app/internal/security/dependencies.py index c33bc8a2..19db881b 100644 --- a/app/internal/security/dependencies.py +++ b/app/internal/security/dependencies.py @@ -1,3 +1,5 @@ +from typing import Optional + from fastapi import Depends, HTTPException from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED @@ -90,3 +92,21 @@ async def current_user( detail="Your token is not valid. Please log in again", ) return schema.CurrentUser(user_id=user_id, username=username) + + +def get_jinja_current_user(request: Request) -> Optional[schema.CurrentUser]: + """Return the currently logged in user. + Returns logged in User object if exists, None if not. + Set as a jinja global parameter. + """ + if "Authorization" not in request.cookies: + return None + jwt_payload = get_jwt_token(request.cookies["Authorization"]) + username = jwt_payload.get("sub") + user_id = jwt_payload.get("user_id") + if not user_id: + raise HTTPException( + status_code=HTTP_401_UNAUTHORIZED, + detail="Your token is not valid. Please log in again", + ) + return schema.CurrentUser(user_id=user_id, username=username) diff --git a/app/main.py b/app/main.py index 0170198e..ccf4c30c 100644 --- a/app/main.py +++ b/app/main.py @@ -6,6 +6,7 @@ from fastapi.staticfiles import StaticFiles from sqlalchemy.orm import Session +import app.internal.features as internal_features from app import config from app.database import engine, models from app.dependencies import ( @@ -13,14 +14,14 @@ SOUNDS_PATH, STATIC_PATH, UPLOAD_PATH, + SessionLocal, get_db, logger, templates, - SessionLocal, ) from app.internal import daily_quotes, json_data_loader -import app.internal.features as internal_features from app.internal.languages import set_ui_language +from app.internal.security.dependencies import get_jinja_current_user from app.internal.security.ouath2 import auth_exception_handler from app.routers.salary import routes as salary from app.utils.extending_openapi import custom_openapi @@ -51,6 +52,7 @@ def create_tables(engine, psql_environment): app.logger = logger app.add_exception_handler(status.HTTP_401_UNAUTHORIZED, auth_exception_handler) +templates.env.globals["jinja_current_user"] = get_jinja_current_user # This MUST come before the app.routers imports. set_ui_language() diff --git a/app/templates/base.html b/app/templates/base.html index 9bf7748d..28cb7456 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -31,21 +31,24 @@