From 5520e7bdba2342a81d04c07741d27b35768d4bab Mon Sep 17 00:00:00 2001 From: Augusto Herrmann Date: Thu, 3 Oct 2024 17:57:11 -0300 Subject: [PATCH] Implement middleware for checking User Agent --- src/api.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/api.py b/src/api.py index b28b5ab..91d480e 100644 --- a/src/api.py +++ b/src/api.py @@ -6,9 +6,9 @@ import os from typing import Annotated, Union -from fastapi import Depends, FastAPI, HTTPException, status, Header, Response +from fastapi import Depends, FastAPI, HTTPException, status, Header, Request, Response from fastapi.security import OAuth2PasswordRequestForm -from fastapi.responses import RedirectResponse +from fastapi.responses import JSONResponse, RedirectResponse from sqlalchemy.exc import IntegrityError @@ -20,7 +20,7 @@ from util import check_permissions ACCESS_TOKEN_EXPIRE_MINUTES = int(os.environ.get("ACCESS_TOKEN_EXPIRE_MINUTES")) -TEST_ENVIRONMENT = os.environ.get("TEST_ENVIRONMENT", 'False') == 'True' +TEST_ENVIRONMENT = os.environ.get("TEST_ENVIRONMENT", "False") == "True" # ## INIT -------------------------------------------------- @@ -55,6 +55,18 @@ async def on_startup(): await crud_auth.init_user_admin() +@app.middleware("http") +async def check_user_agent(request: Request, call_next): + user_agent = request.headers.get("User-Agent", None) + + if not user_agent: + return JSONResponse( + status_code=400, + content={"detail": "User-Agent header is required"}, + ) + return await call_next(request) + + @app.get("/", include_in_schema=False) async def docs_redirect( accept: Union[str, None] = Header(default="text/html")