PYDANTIC max_length (38 Routen, ~400 Field-Constraints): Schützt vor DoS durch Riesen-Payloads (10MB Thread-Titel etc.). Pragmatische Limits: - Titel/Name: 200 · Beschreibung/Body: 10000 · Notiz: 5000 - Email: 254 (RFC 5321) · URL: 500 · Slug/Kategorie: 100 - Hund-Name/Rasse: 80 · Hund-Bio: 2000 Top-betroffen: forum.py, diary.py, health.py, dogs.py, expenses.py, notes.py, auth.py, profile.py. Manuelle len()-Checks in profile, chat, ki entfernt (jetzt durch Field abgedeckt). PYTEST COVERAGE (+19 Tests, 37 grün + 1 xfail): - test_security.py: require_owner (Places GET/PATCH/DELETE mit Fremduser → 403), JWT-Blacklist (Logout invalidiert Token), Login-Lockout (5 Fehlversuche → 429 + Retry-After Header) - test_race.py: Invoice-Counter (20 parallele Threads, alle unique), Founder-Number (atomare Vergabe, voll bei 100) - test_validation.py: Forum-Titel 30k Zeichen → 422, Diary-Text 50k → 422 (verifiziert Pydantic max_length-Sweep) A11Y (Tap-Targets ≥44×44 + Dark-Mode-Kontrast): - #header-user-btn 36→44px, .header-back 40→44, .header-menu-btn 40→44 - dog-profile Wrapped-Slider Prev/Next 40→44 - forum-Lightbox Close 40→44 - --c-text-muted Light: #B0A090 (2.37:1 FAIL) → #7F6B58 (4.74:1 PASS) - --c-text-muted Dark: #806A58 (3.58:1 FAIL) → #A08878 (5.46:1 PASS) - Branding-Farben unangetastet
156 lines
6.3 KiB
Python
156 lines
6.3 KiB
Python
"""BAN YARO — Hundefreundliche Orte"""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from pydantic import BaseModel, Field
|
|
from typing import Optional
|
|
from database import db
|
|
from auth import get_current_user, require_owner
|
|
from math_utils import haversine_m
|
|
|
|
router = APIRouter()
|
|
|
|
TYPEN = {'restaurant', 'shop', 'freilauf', 'kotbeutel', 'tierarzt', 'hundesalon', 'hundeschule'}
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# Schemas
|
|
# ------------------------------------------------------------------
|
|
class PlaceCreate(BaseModel):
|
|
name: str = Field(..., min_length=1, max_length=200)
|
|
typ: str = Field(..., max_length=50)
|
|
lat: float
|
|
lon: float
|
|
adresse: Optional[str] = Field(None, max_length=300)
|
|
website: Optional[str] = Field(None, max_length=500)
|
|
telefon: Optional[str] = Field(None, max_length=30)
|
|
hund_rein: Optional[bool] = None
|
|
leine_pflicht: Optional[bool] = None
|
|
wasser_fuer_hunde: Optional[bool] = None
|
|
|
|
class PlaceUpdate(BaseModel):
|
|
name: Optional[str] = Field(None, max_length=200)
|
|
typ: Optional[str] = Field(None, max_length=50)
|
|
lat: Optional[float]= None
|
|
lon: Optional[float]= None
|
|
adresse: Optional[str] = Field(None, max_length=300)
|
|
website: Optional[str] = Field(None, max_length=500)
|
|
telefon: Optional[str] = Field(None, max_length=30)
|
|
hund_rein: Optional[bool] = None
|
|
leine_pflicht: Optional[bool] = None
|
|
wasser_fuer_hunde: Optional[bool] = None
|
|
|
|
|
|
def _row_to_dict(row) -> dict:
|
|
d = dict(row)
|
|
for k in ('hund_rein', 'leine_pflicht', 'wasser_fuer_hunde'):
|
|
if d.get(k) is not None:
|
|
d[k] = bool(d[k])
|
|
return d
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# GET /api/places — alle Orte (optional: Umkreis + Typ-Filter)
|
|
# ------------------------------------------------------------------
|
|
@router.get("")
|
|
async def list_places(
|
|
lat: Optional[float] = None,
|
|
lon: Optional[float] = None,
|
|
radius: int = 5000,
|
|
typ: Optional[str] = None,
|
|
):
|
|
with db() as conn:
|
|
q = "SELECT p.*, u.name AS user_name FROM places p LEFT JOIN users u ON u.id = p.user_id"
|
|
params = []
|
|
if typ:
|
|
q += " WHERE p.typ = ?"
|
|
params.append(typ)
|
|
q += " ORDER BY p.created_at DESC"
|
|
rows = conn.execute(q, params).fetchall()
|
|
|
|
result = [_row_to_dict(r) for r in rows]
|
|
if lat is not None and lon is not None:
|
|
result = [r for r in result if haversine_m(lat, lon, r['lat'], r['lon']) <= radius]
|
|
return result
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# POST /api/places — neuen Ort anlegen (Login erforderlich)
|
|
# ------------------------------------------------------------------
|
|
@router.post("", status_code=201)
|
|
async def create_place(data: PlaceCreate, user=Depends(get_current_user)):
|
|
if data.typ not in TYPEN:
|
|
raise HTTPException(400, f"Ungültiger Typ. Erlaubt: {', '.join(sorted(TYPEN))}")
|
|
with db() as conn:
|
|
cur = conn.execute("""
|
|
INSERT INTO places
|
|
(user_id, name, typ, lat, lon, adresse, website, telefon,
|
|
hund_rein, leine_pflicht, wasser_fuer_hunde)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""", (
|
|
user['id'], data.name, data.typ, data.lat, data.lon,
|
|
data.adresse, data.website, data.telefon,
|
|
int(data.hund_rein) if data.hund_rein is not None else None,
|
|
int(data.leine_pflicht) if data.leine_pflicht is not None else None,
|
|
int(data.wasser_fuer_hunde) if data.wasser_fuer_hunde is not None else None,
|
|
))
|
|
row = conn.execute(
|
|
"SELECT p.*, u.name AS user_name FROM places p LEFT JOIN users u ON u.id = p.user_id WHERE p.id = ?",
|
|
(cur.lastrowid,)
|
|
).fetchone()
|
|
return _row_to_dict(row)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# GET /api/places/{id}
|
|
# ------------------------------------------------------------------
|
|
@router.get("/{place_id}")
|
|
async def get_place(place_id: int):
|
|
with db() as conn:
|
|
row = conn.execute(
|
|
"SELECT p.*, u.name AS user_name FROM places p LEFT JOIN users u ON u.id = p.user_id WHERE p.id = ?",
|
|
(place_id,)
|
|
).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, "Ort nicht gefunden.")
|
|
return _row_to_dict(row)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# PATCH /api/places/{id} — bearbeiten (nur eigene)
|
|
# ------------------------------------------------------------------
|
|
@router.patch("/{place_id}")
|
|
async def update_place(place_id: int, data: PlaceUpdate, user=Depends(get_current_user)):
|
|
with db() as conn:
|
|
row = require_owner(
|
|
conn.execute("SELECT * FROM places WHERE id = ?", (place_id,)).fetchone(),
|
|
user, not_found_msg="Ort nicht gefunden.", forbidden_msg="Nicht berechtigt."
|
|
)
|
|
|
|
updates = data.model_dump(exclude_none=True)
|
|
if not updates:
|
|
return _row_to_dict(row)
|
|
|
|
for key in ('hund_rein', 'leine_pflicht', 'wasser_fuer_hunde'):
|
|
if key in updates:
|
|
updates[key] = int(updates[key])
|
|
|
|
cols = ', '.join(f"{k} = ?" for k in updates)
|
|
conn.execute(f"UPDATE places SET {cols} WHERE id = ?", [*updates.values(), place_id])
|
|
row = conn.execute(
|
|
"SELECT p.*, u.name AS user_name FROM places p LEFT JOIN users u ON u.id = p.user_id WHERE p.id = ?",
|
|
(place_id,)
|
|
).fetchone()
|
|
return _row_to_dict(row)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# DELETE /api/places/{id}
|
|
# ------------------------------------------------------------------
|
|
@router.delete("/{place_id}", status_code=204)
|
|
async def delete_place(place_id: int, user=Depends(get_current_user)):
|
|
with db() as conn:
|
|
require_owner(
|
|
conn.execute("SELECT * FROM places WHERE id = ?", (place_id,)).fetchone(),
|
|
user, not_found_msg="Ort nicht gefunden.", forbidden_msg="Nicht berechtigt."
|
|
)
|
|
conn.execute("DELETE FROM places WHERE id = ?", (place_id,))
|