From 60a54a5363e50e5e82378deb53d5d2b629631ce1 Mon Sep 17 00:00:00 2001 From: FrederikBaerentsen Date: Tue, 9 Sep 2025 14:24:35 +0200 Subject: [PATCH] Fixed auth --- app/auth.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/app/auth.py b/app/auth.py index aa39c3d..df3eccc 100644 --- a/app/auth.py +++ b/app/auth.py @@ -1,6 +1,7 @@ -import os -from fastapi import HTTPException, Request +from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials +import secrets +import os security = HTTPBasic() @@ -8,12 +9,18 @@ DISABLE_AUTH = os.getenv("DISABLE_AUTH", "false").strip().lower() in ("1","true" USER = os.getenv("OPDS_BASIC_USER", "").strip() PASS = os.getenv("OPDS_BASIC_PASS", "").strip() -def require_basic(request: Request, credentials: HTTPBasicCredentials = None): - # If disabled, or no credentials configured at all, allow through - if DISABLE_AUTH or not USER or not PASS: - return - if credentials is None: - credentials = security(request) - if not (credentials.username == USER and credentials.password == PASS): - raise HTTPException(status_code=401, detail="Not authenticated", - headers={"WWW-Authenticate": "Basic"}) +async def require_basic(credentials: HTTPBasicCredentials = Depends(security)): + if DISABLE_AUTH: + return True + + # Use secrets.compare_digest to avoid timing attacks + correct_user = secrets.compare_digest(credentials.username, USER or "") + correct_pass = secrets.compare_digest(credentials.password, PASS or "") + + if not (correct_user and correct_pass): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid credentials", + headers={"WWW-Authenticate": "Basic"}, + ) + return True \ No newline at end of file