From f4d843a60749d51d0ba1a7d7b33f286dce03fa22 Mon Sep 17 00:00:00 2001 From: msramalho <19508417+msramalho@users.noreply.github.com> Date: Tue, 28 Feb 2023 10:25:37 +0100 Subject: [PATCH] secure auth --- src/main.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/main.py b/src/main.py index e1e829a..566c2d5 100644 --- a/src/main.py +++ b/src/main.py @@ -4,10 +4,11 @@ from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse, FileResponse from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware +from fastapi.security import HTTPBasic, HTTPBasicCredentials # from fastapi.templating import Jinja2Templates # from pydantic.json import pydantic_encoder from dotenv import load_dotenv -import traceback, os, requests, re +import traceback, os, requests, re, secrets from loguru import logger from worker import create_archive_task, celery @@ -24,7 +25,7 @@ assert len(GOOGLE_CHROME_APP_ID)>10, "GOOGLE_CHROME_APP_ID env variable not set" ALLOWED_EMAILS = set(os.environ.get("ALLOWED_EMAILS", "").split(",")) assert len(GOOGLE_CHROME_APP_ID)>=1, "at least one ALLOWED_EMAILS is required from the env variable" ALLOWED_ORIGINS = os.environ.get("ALLOWED_ORIGINS", "chrome-extension://ondkcheoicfckabcnkdgbepofpjmjcmb,chrome-extension://ojcimmjndnlmmlgnjaeojoebaceokpdp").split(",") -VERSION = "0.1.7" +VERSION = "0.1.8" app = FastAPI() app.add_middleware( @@ -99,14 +100,18 @@ def get_status(task_id, access_token:str, db: Session = Depends(get_db)): # logic to allow access to 1 static file SF = os.environ.get("STATIC_FILE", "") SFP = os.environ.get("STATIC_FILE_PASSWORD", "") # min length is 20 chars +security = HTTPBasic() if len(SF) > 1 and len(SFP) >= 20 and os.path.isfile(SF): @app.get("/static-file") - def static_file(static_file_password:str): - if type(static_file_password) ==str and len(static_file_password)>=20 and static_file_password==SFP: + def static_file(credentials: HTTPBasicCredentials = Depends(security)): + current_password_bytes = credentials.password.encode("utf8") + is_correct_password = secrets.compare_digest(current_password_bytes, SFP.encode("utf8")) + if is_correct_password: return FileResponse(SF, filename=os.path.basename(SF)) raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, - detail="Wrong static file access credentials" + detail="Wrong static file access credentials", + headers={"WWW-Authenticate": "Basic"} ) @app.get("/")