From c9b3f7d33c3ed0defb528bb214481472d29e4938 Mon Sep 17 00:00:00 2001 From: Matteo Rosati Date: Tue, 20 Jan 2026 12:07:16 +0100 Subject: [PATCH] add basic auth --- app.py | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/app.py b/app.py index dc1c0de..2c5dd2d 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,8 @@ import os import logging -from fastapi import FastAPI, Request, WebSocket +from typing import Annotated +from fastapi import FastAPI, Request, WebSocket, Depends, HTTPException, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles from main import generate @@ -17,6 +19,8 @@ logger = logging.getLogger(__name__) STATIC_DIR = "static" TEMPLATES_DIR = "templates" +security = HTTPBasic() + app = FastAPI() app.mount(f"/{STATIC_DIR}", StaticFiles(directory=STATIC_DIR), name="static") @@ -24,8 +28,24 @@ app.mount(f"/{STATIC_DIR}", StaticFiles(directory=STATIC_DIR), name="static") templates = Jinja2Templates(directory=os.path.join(STATIC_DIR, TEMPLATES_DIR)) +def verify_credentials(credentials: HTTPBasicCredentials = Depends(security)): + correct_username = os.getenv("BASIC_AUTH_USERNAME") + correct_password = os.getenv("BASIC_AUTH_PASSWORD") + + if not ( + credentials.username == correct_username + and credentials.password == correct_password + ): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Basic"}, + ) + return credentials.username + + @app.get("/") -async def home(request: Request): +async def home(request: Request, username: Annotated[str, Depends(verify_credentials)]): return templates.TemplateResponse("index.html", {"request": request})