feat: FastAPI-App mit API-Key- und Session-Auth

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-17 18:03:24 +02:00
parent 101ee01af1
commit a10f4d0b57
4 changed files with 126 additions and 1 deletions

53
finance/app/auth.py Normal file
View File

@@ -0,0 +1,53 @@
import hashlib
import hmac
import secrets
from fastapi import HTTPException, Request
from itsdangerous import BadSignature, TimestampSigner
from app.config import get_settings
COOKIE = "fb_session"
MAX_AGE = 60 * 60 * 12 # 12 h
def hash_password(pw: str, salt: str | None = None) -> str:
salt = salt or secrets.token_hex(16)
digest = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 200_000).hex()
return f"{salt}${digest}"
def verify_password(pw: str, stored: str) -> bool:
try:
salt, digest = stored.split("$", 1)
except ValueError:
return False
return hmac.compare_digest(hash_password(pw, salt).split("$", 1)[1], digest)
def _signer() -> TimestampSigner:
return TimestampSigner(get_settings().session_secret)
def make_session_token() -> str:
return _signer().sign(b"gui").decode()
def session_valid(token: str | None) -> bool:
if not token:
return False
try:
_signer().unsign(token, max_age=MAX_AGE)
return True
except BadSignature:
return False
def require_auth(request: Request) -> None:
settings = get_settings()
header = request.headers.get("authorization", "")
if settings.api_key and header == f"Bearer {settings.api_key}":
return
if session_valid(request.cookies.get(COOKIE)):
return
raise HTTPException(status_code=401, detail="Nicht angemeldet")

41
finance/app/main.py Normal file
View File

@@ -0,0 +1,41 @@
import hmac
from fastapi import Depends, FastAPI, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from app import auth
from app.config import get_settings
app = FastAPI(title="Finanzberatungs-Tool")
@app.get("/login", response_class=HTMLResponse)
def login_form():
return """<form method=post action=/login>
<input name=username placeholder=Benutzer>
<input name=password type=password placeholder=Passwort>
<button>Anmelden</button></form>"""
@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
s = get_settings()
if not (hmac.compare_digest(username, s.gui_user)
and auth.verify_password(password, s.gui_password_hash)):
return HTMLResponse("Login fehlgeschlagen", status_code=401)
resp = RedirectResponse("/", status_code=303)
resp.set_cookie(auth.COOKIE, auth.make_session_token(), httponly=True,
max_age=auth.MAX_AGE, samesite="lax")
return resp
@app.post("/logout")
def logout():
resp = RedirectResponse("/login", status_code=303)
resp.delete_cookie(auth.COOKIE)
return resp
@app.get("/api/accounts", dependencies=[Depends(auth.require_auth)])
def _placeholder_accounts(): # wird in Task 9 durch Router ersetzt
return []