Etappe 5: Auth + Rate-Limiting
- JWT-Auth (Access 15min/Refresh 7 Tage) - Rate-Limiting (100/min pro Client/API-Key) - API Key Management - OAuth2 Password Scheme
This commit is contained in:
+121
-1
@@ -1,4 +1,4 @@
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi import FastAPI, HTTPException, Request, Response
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import StreamingResponse
|
||||
from fastapi import WebSocket, WebSocketDisconnect
|
||||
@@ -9,9 +9,14 @@ import os
|
||||
import subprocess
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
|
||||
from .config import settings
|
||||
from .cache import init_cache, set
|
||||
from .auth import create_access_token, create_refresh_token, decode_token, is_blacklisted
|
||||
from .ratelimit import check_rate_limit, get_rate_limit_remaining, validate_api_key
|
||||
from .prescan import PreScan
|
||||
from .nfo_generator import NFOGenerator
|
||||
from .image_downloader import ImageDownloader
|
||||
@@ -22,6 +27,9 @@ app = FastAPI(
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# OAuth2 Scheme
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
# SSE-Connections
|
||||
sse_connections: List = []
|
||||
|
||||
@@ -31,6 +39,36 @@ async def startup_event():
|
||||
"""Initialisiere Cache beim Start."""
|
||||
init_cache()
|
||||
|
||||
|
||||
# Middleware für Rate-Limiting
|
||||
@app.middleware("http")
|
||||
async def rate_limit_middleware(request: Request, call_next):
|
||||
"""Rate-Limiting Middleware."""
|
||||
client_ip = request.client.host
|
||||
api_key = request.headers.get("X-API-Key")
|
||||
|
||||
# Prüfe API Key
|
||||
if api_key:
|
||||
key_info = validate_api_key(api_key)
|
||||
if not key_info:
|
||||
raise HTTPException(status_code=401, detail="Ungültiger API Key")
|
||||
|
||||
# Rate Limit prüfen
|
||||
if not check_rate_limit(client_ip):
|
||||
return Response(
|
||||
content=json.dumps({"error": "Rate limit exceeded"}),
|
||||
status_code=429,
|
||||
media_type="application/json"
|
||||
)
|
||||
|
||||
response = await call_next(request)
|
||||
|
||||
# Füge Rate-Limit Header hinzu
|
||||
remaining = get_rate_limit_remaining(client_ip)
|
||||
response.headers["X-RateLimit-Remaining"] = str(remaining)
|
||||
|
||||
return response
|
||||
|
||||
# CORS hinzufügen
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
@@ -249,3 +287,85 @@ async def jellyfin_format(request: JellyfinFormatRequest):
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
# Auth Endpoints
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
@app.post("/token")
|
||||
async def login(request: LoginRequest):
|
||||
"""Login und Token generieren."""
|
||||
# Einfache Auth für MVP (in Produktion mit Datenbank)
|
||||
if request.username == "admin" and request.password == "rippy123":
|
||||
access_token = create_access_token(
|
||||
data={"sub": request.username, "scopes": ["admin"]}
|
||||
)
|
||||
refresh_token = create_refresh_token(
|
||||
data={"sub": request.username}
|
||||
)
|
||||
return {
|
||||
"access_token": access_token,
|
||||
"refresh_token": refresh_token,
|
||||
"token_type": "bearer"
|
||||
}
|
||||
raise HTTPException(status_code=401, detail="Ungültige Anmeldedaten")
|
||||
|
||||
|
||||
@app.post("/token/refresh")
|
||||
async def refresh_token(refresh_token: str):
|
||||
"""Refresh Access Token."""
|
||||
payload = decode_token(refresh_token)
|
||||
if not payload or payload.get("type") != "refresh":
|
||||
raise HTTPException(status_code=401, detail="Ungültiges Refresh Token")
|
||||
|
||||
access_token = create_access_token(
|
||||
data={"sub": payload.get("sub"), "scopes": payload.get("scopes", [])}
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
|
||||
@app.post("/token/invalidate")
|
||||
async def invalidate_token(token: str):
|
||||
"""Invalidate Token (Logout)."""
|
||||
if is_blacklisted(token):
|
||||
raise HTTPException(status_code=400, detail="Token bereits invalidiert")
|
||||
|
||||
# In Produktion mit Redis implementieren
|
||||
return {"status": "invalidated"}
|
||||
|
||||
|
||||
# API Key Endpoints
|
||||
class APIKeyCreateRequest(BaseModel):
|
||||
name: str
|
||||
|
||||
|
||||
@app.post("/api-keys")
|
||||
async def create_api_key(request: APIKeyCreateRequest):
|
||||
"""Erstelle API Key."""
|
||||
# In Produktion mit Auth prüfen
|
||||
key_info = {
|
||||
"key": secrets.token_urlsafe(32),
|
||||
"name": request.name,
|
||||
"created_at": time.time(),
|
||||
"rate_limit": 100
|
||||
}
|
||||
return key_info
|
||||
|
||||
|
||||
@app.get("/api-keys")
|
||||
async def list_api_keys():
|
||||
"""Liste API Keys."""
|
||||
return list(api_keys.values())
|
||||
|
||||
|
||||
@app.delete("/api-keys/{key}")
|
||||
async def delete_api_key(key: str):
|
||||
"""Lösche API Key."""
|
||||
# In Produktion mit Auth prüfen
|
||||
if key in api_keys:
|
||||
del api_keys[key]
|
||||
return {"status": "deleted"}
|
||||
raise HTTPException(status_code=404, detail="API Key nicht gefunden")
|
||||
|
||||
Reference in New Issue
Block a user