From a331a60ad8a27663c4b9fad487a164eadb189ef7 Mon Sep 17 00:00:00 2001 From: Mariano Censi Date: Mon, 4 Aug 2025 10:28:33 -0300 Subject: [PATCH] Added basic security Basic http login for the api --- .env.example | 2 ++ api/auth.py | 20 ++++++++++++++++++++ api/file.py | 3 ++- api/folder.py | 3 ++- main.py | 2 ++ requirements.txt | 3 ++- 6 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 .env.example create mode 100644 api/auth.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e101f67 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +USERNAME= +PASSWORD= \ No newline at end of file diff --git a/api/auth.py b/api/auth.py new file mode 100644 index 0000000..e0d7450 --- /dev/null +++ b/api/auth.py @@ -0,0 +1,20 @@ +from fastapi import FastAPI, Depends, HTTPException, status +from fastapi.security import HTTPBasic, HTTPBasicCredentials +from fastapi.staticfiles import StaticFiles +import secrets +from os import getenv + +USERNAME = getenv('USERNAME') +PASSWORD = getenv('PASSWORD') + +security = HTTPBasic() +def authenticate(credentials: HTTPBasicCredentials = Depends(security)): + correct_username = secrets.compare_digest(credentials.username, USERNAME) + correct_password = secrets.compare_digest(credentials.password, PASSWORD) + if not (correct_username and correct_password): + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Unauthorized :/", + headers={"WWW-Authenticate": "Basic"}, + ) + return credentials.username \ No newline at end of file diff --git a/api/file.py b/api/file.py index 6731303..1365c46 100644 --- a/api/file.py +++ b/api/file.py @@ -4,8 +4,9 @@ import pathlib from . import schemas from datetime import datetime +from . import auth -file = APIRouter(tags=["file"]) +file = APIRouter(tags=["file"], dependencies=[Depends(auth.authenticate)]) @file.get("{url_path:path}", response_class=FileResponse, summary="download") diff --git a/api/folder.py b/api/folder.py index 7da5cd9..371f391 100644 --- a/api/folder.py +++ b/api/folder.py @@ -5,8 +5,9 @@ import pathlib from datetime import datetime from typing import Union, List +from . import auth -folder = APIRouter(tags=["folder"]) +folder = APIRouter(tags=["folder"], dependencies=[Depends(auth.authenticate)]) LS = List[Union[schemas.sys_file, schemas.sys_folder]] diff --git a/main.py b/main.py index 87ee6b3..ba4f173 100644 --- a/main.py +++ b/main.py @@ -4,7 +4,9 @@ from pathlib import Path import api # import core +from dotenv import load_dotenv +load_dotenv() app = FastAPI(title='FFServer API', description=""" It's not safe at all. Use it on your home WLAN. diff --git a/requirements.txt b/requirements.txt index dfc0787..22587e5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,5 @@ fastapi pydantic python-multipart uvicorn -filetype \ No newline at end of file +filetype +dotenv \ No newline at end of file