Files
certain/backend/app/routers/backup.py
T
ScarriffleandClaude Opus 5 e503baa8a6 fix: sprechende Dateinamen fuer alle Exporte
Im Downloads-Ordner lagen "certain-finance-export_....json" und
"certain-finance-backup_....json" nebeneinander, ohne dass man sah, welche
Datei sich zurueckladen laesst. Alle Downloads heissen jetzt
certain-finance_<art>_<datum>_<uhrzeit>.<endung>, wobei die Art es sagt:
vollbackup, vollbackup-system, datenuebersicht, buchungen, datenbank. Das
persoenliche Vollbackup traegt zusaetzlich den Benutzernamen.

Den Namen vergibt jetzt allein der Server im Content-Disposition-Kopf; das
Frontend liest ihn von dort. Vorher erfanden beide Seiten ihn getrennt und
kamen auf unterschiedliche Ergebnisse (Bindestrich gegen Unterstrich, UTC
gegen Ortszeit). Zeitstempel ist Ortszeit: wer abends um 20 Uhr exportiert,
soll keine Datei von 18 Uhr finden.

Passend dazu heisst der Knopf "Alle Daten (JSON)" nun "Datenuebersicht
(JSON)", und der Hinweis darueber sagt ausdruecklich, dass sich diese
Dateien nicht zurueckladen lassen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 13:13:39 +02:00

393 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Backup & Export: kompletter DB-Download (Admin), Datenexport je Nutzer und
das wiederherstellbare Voll-Backup als JSON (siehe ``services/backup_data``)."""
import csv
import io
import os
import re
import sqlite3
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from fastapi import APIRouter, Depends, File, Form, HTTPException, Response, UploadFile
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from starlette.background import BackgroundTask
from ..config import get_settings
from ..database import get_db
from ..deps import get_current_user, require_admin
from ..models import (
Account,
AccountIdentifier,
BudgetTemplateLine,
Category,
CategoryGroup,
DashboardLayout,
PlannedIncomeLine,
Role,
Transaction,
User,
)
from ..services import backup_data, sessions
router = APIRouter(tags=["backup"])
# Ein Backup ist reiner Text; alles darüber ist mit Sicherheit keins mehr.
MAX_BACKUP_BYTES = 64 * 1024 * 1024
def _ts() -> str:
"""Ortszeit als ``YYYY-MM-DD_HHMM`` – Dateinamen sollen lesbar sein.
Bewusst nicht UTC: wer abends um 20 Uhr exportiert, soll im Downloads-Ordner
keine Datei von 18 Uhr finden."""
return datetime.now().astimezone().strftime("%Y-%m-%d_%H%M")
def _dateiname(art: str, endung: str) -> str:
"""Einheitlicher, sprechender Dateiname für alle Downloads.
``art`` muss erkennen lassen, worum es geht – im Downloads-Ordner liegen die
Dateien sonst nebeneinander und man sieht ihnen nicht an, welche sich
zurückladen lässt (``vollbackup``) und welche nur zum Ansehen taugt
(``datenuebersicht``)."""
return f"certain-finance_{art}_{_ts()}.{endung}"
def _namensteil(text: str) -> str:
"""Beliebigen Text auf etwas eindampfen, das in einem Dateinamen taugt."""
sauber = re.sub(r"[^A-Za-z0-9]+", "-", text).strip("-").lower()
return sauber[:32] or "unbekannt"
def _sqlite_path() -> str | None:
url = get_settings().effective_database_url
return url.replace("sqlite:///", "", 1) if url.startswith("sqlite:///") else None
def _snapshot_before_restore() -> str | None:
"""Legt vor einem ersetzenden Restore eine Kopie der Datenbank ab.
Dieselbe Absicherung, die ``deploy/update.sh`` vor einem Update macht: wer
versehentlich das falsche Backup einspielt, hat noch einen Weg zurück."""
db_path = _sqlite_path()
if db_path is None or not os.path.exists(db_path):
return None
ziel_ordner = Path(get_settings().data_dir) / "backups"
ziel_ordner.mkdir(parents=True, exist_ok=True)
ziel = ziel_ordner / f"pre-restore-{_ts()}.db"
src = sqlite3.connect(db_path)
dst = sqlite3.connect(str(ziel))
try:
with dst:
src.backup(dst)
finally:
dst.close()
src.close()
return str(ziel)
def _money(cents: int | None) -> str:
return f"{(cents or 0) / 100:.2f}"
# --- Komplettes DB-Backup (nur Admin) --------------------------------------
@router.get("/backup/db")
def backup_db(_: User = Depends(require_admin)):
db_path = _sqlite_path()
if db_path is None:
raise HTTPException(status_code=400, detail="DB-Backup ist nur für SQLite verfügbar.")
tmp = tempfile.NamedTemporaryFile(prefix="cf-backup-", suffix=".db", delete=False)
tmp.close()
# Online-Backup-API: konsistente Kopie auch bei laufendem Betrieb.
src = sqlite3.connect(db_path)
dst = sqlite3.connect(tmp.name)
try:
with dst:
src.backup(dst)
finally:
dst.close()
src.close()
return FileResponse(
tmp.name,
media_type="application/octet-stream",
filename=_dateiname("datenbank", "db"),
background=BackgroundTask(os.remove, tmp.name),
)
# --- Transaktionsexport ----------------------------------------------------
def _maps(db: Session, user: User) -> tuple[dict[int, Account], dict[int, Category]]:
accs = {a.id: a for a in db.query(Account).filter(Account.owner_id == user.id)}
cats = {c.id: c for c in db.query(Category).filter(Category.owner_id == user.id)}
return accs, cats
def _txns(db: Session, user: User) -> list[Transaction]:
return (
db.query(Transaction)
.filter(Transaction.owner_id == user.id)
.order_by(Transaction.date, Transaction.id)
.all()
)
@router.get("/export/transactions.csv")
def export_transactions_csv(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
buf = io.StringIO()
w = csv.writer(buf, delimiter=";")
w.writerow(["Datum", "Typ", "Konto", "Betrag", "Waehrung", "EUR-Wert",
"Zielkonto", "Kategorie", "Empfaenger", "Verwendungszweck", "Notiz"])
for t in _txns(db, user):
acc = accs.get(t.account_id)
w.writerow([
t.date.isoformat(), t.type.value, acc.name if acc else "",
_money(t.amount_cents), acc.currency if acc else "", _money(t.amount_eur_cents),
accs[t.to_account_id].name if t.to_account_id and t.to_account_id in accs else "",
cats[t.category_id].name if t.category_id and t.category_id in cats else "",
t.payee or "", t.description or "", t.notes or "",
])
return Response(
content=buf.getvalue().encode("utf-8-sig"),
media_type="text/csv",
headers={"Content-Disposition": f'attachment; filename="{_dateiname("buchungen", "csv")}"'},
)
def _txn_dict(t: Transaction, accs: dict[int, Account], cats: dict[int, Category]) -> dict:
acc = accs.get(t.account_id)
return {
"date": t.date.isoformat(),
"type": t.type.value,
"account": acc.name if acc else None,
"currency": acc.currency if acc else None,
"amount_cents": t.amount_cents,
"amount_eur_cents": t.amount_eur_cents,
"to_account": accs[t.to_account_id].name if t.to_account_id in accs else None,
"to_amount_cents": t.to_amount_cents,
"category": cats[t.category_id].name if t.category_id in cats else None,
"payee": t.payee,
"description": t.description,
"notes": t.notes,
}
@router.get("/export/transactions.json")
def export_transactions_json(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
data = [_txn_dict(t, accs, cats) for t in _txns(db, user)]
return Response(
content=_json_bytes(data),
media_type="application/json",
headers={"Content-Disposition": f'attachment; filename="{_dateiname("buchungen", "json")}"'},
)
# --- Gesamt-Export (alle eigenen Daten als JSON) ---------------------------
def _json_bytes(obj) -> bytes:
import json
return json.dumps(obj, ensure_ascii=False, indent=2).encode("utf-8")
@router.get("/export/all.json")
def export_all_json(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
accs, cats = _maps(db, user)
idents: dict[int, list] = {}
for i in db.query(AccountIdentifier).join(Account).filter(Account.owner_id == user.id):
idents.setdefault(i.account_id, []).append({"kind": i.kind.value, "value": i.value})
accounts = [{
"name": a.name, "type": a.type.value, "currency": a.currency,
"opening_balance_cents": a.opening_balance_cents,
"opening_date": a.opening_date.isoformat() if a.opening_date else None,
"icon": a.icon, "color": a.color, "archived": a.is_archived,
"identifiers": idents.get(a.id, []),
} for a in accs.values()]
groups = []
for g in db.query(CategoryGroup).filter(CategoryGroup.owner_id == user.id).order_by(CategoryGroup.position):
groups.append({
"name": g.name, "kind": g.kind.value, "icon": g.icon, "color": g.color,
"categories": [
{"name": c.name, "icon": c.icon, "color": c.color}
for c in sorted(g.categories, key=lambda x: x.position)
],
})
budget_template = [
{"category": cats[l.category_id].name if l.category_id in cats else None, "planned_cents": l.planned_cents}
for l in db.query(BudgetTemplateLine).filter(BudgetTemplateLine.owner_id == user.id)
]
planned_income = [
{"label": l.label, "planned_cents": l.planned_cents,
"category": cats[l.category_id].name if l.category_id in cats else None,
"target_account": accs[l.target_account_id].name if l.target_account_id in accs else None}
for l in db.query(PlannedIncomeLine).filter(PlannedIncomeLine.owner_id == user.id)
]
dash = db.query(DashboardLayout).filter(DashboardLayout.owner_id == user.id).first()
data = {
"exported_at": datetime.now(timezone.utc).isoformat(),
"app": "Certain Finance",
"user": user.username,
"accounts": accounts,
"category_groups": groups,
"transactions": [_txn_dict(t, accs, cats) for t in _txns(db, user)],
"budget_template": budget_template,
"planned_income": planned_income,
"dashboard_layout": dash.layout if dash else None,
}
return Response(
content=_json_bytes(data),
media_type="application/json",
# „datenuebersicht", nicht „backup": diese Datei lässt sich bewusst
# nicht zurückladen (siehe services/backup_data.parse).
headers={
"Content-Disposition": f'attachment; filename="{_dateiname("datenuebersicht", "json")}"'
},
)
# --- Voll-Backup (wiederherstellbar) ---------------------------------------
def _download(obj: dict, dateiname: str) -> Response:
return Response(
content=backup_data.to_bytes(obj),
media_type="application/json",
headers={"Content-Disposition": f'attachment; filename="{dateiname}"'},
)
@router.get("/export/backup.json")
def export_backup(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
"""Alle eigenen Daten – vollständig und wieder einspielbar.
Der Benutzername steht im Dateinamen: bei mehreren Konten liegen sonst
gleichnamige Backups im selben Ordner."""
return _download(
backup_data.export_user(db, user),
_dateiname(f"vollbackup_{_namensteil(user.username)}", "json"),
)
@router.get("/export/system-backup.json")
def export_system_backup(db: Session = Depends(get_db), _: User = Depends(require_admin)):
"""Die ganze Instanz inklusive Benutzerkonten. Enthält Passwort-Hashes und
TOTP-Secrets – die Datei ist wie ein Passwort zu behandeln."""
return _download(backup_data.export_system(db), _dateiname("vollbackup-system", "json"))
async def _read_upload(file: UploadFile) -> bytes:
roh = await file.read()
if len(roh) > MAX_BACKUP_BYTES:
raise HTTPException(status_code=400, detail="Die Datei ist zu gross für ein Backup.")
return roh
@router.post("/backup/restore/preview")
async def restore_preview(
file: UploadFile = File(...),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Prüft die Datei und meldet, was darin steckt. Schreibt nichts."""
try:
data = backup_data.parse(await _read_upload(file))
except backup_data.BackupError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
scope = data["scope"]
if scope == "system" and user.role != Role.admin:
raise HTTPException(
status_code=403,
detail="Ein systemweites Backup darf nur ein Administrator einspielen.",
)
hinweise: list[str] = []
if scope == "system":
hinweise.append(
"Systemweite Wiederherstellung: alle Benutzer und deren Daten werden "
"ersetzt. Danach sind alle Sitzungen beendet und du musst dich neu anmelden."
)
if not any(u.get("role") == "admin" for u in data.get("users") or []):
hinweise.append("Achtung: im Backup ist kein Administrator enthalten.")
return {
"scope": scope,
"exported_at": data.get("exported_at"),
"app_version": data.get("app_version"),
"username": data.get("username"),
"user_count": len(data.get("users") or []) if scope == "system" else 1,
"tables": backup_data.summarize(data),
"notes": hinweise,
}
@router.post("/backup/restore")
async def restore(
file: UploadFile = File(...),
mode: str = Form("replace"),
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Spielt ein Backup ein – ``replace`` (ersetzen) oder ``merge`` (ergänzen).
Alles läuft in einer Transaktion: entweder es geht komplett durch oder es
wird gar nichts geschrieben."""
if mode not in ("replace", "merge"):
raise HTTPException(status_code=400, detail="Unbekannter Modus.")
try:
data = backup_data.parse(await _read_upload(file))
except backup_data.BackupError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
scope = data["scope"]
if scope == "system" and user.role != Role.admin:
raise HTTPException(
status_code=403,
detail="Ein systemweites Backup darf nur ein Administrator einspielen.",
)
if scope == "system" and mode != "replace":
raise HTTPException(
status_code=400,
detail="Ein systemweites Backup kann nur ersetzend eingespielt werden.",
)
schnappschuss = _snapshot_before_restore() if mode == "replace" else None
try:
if scope == "system":
bilanz = backup_data.restore_system(db, data)
else:
bilanz = backup_data.restore_user_data(
db, user, data.get("data") or {}, merge=(mode == "merge")
)
db.commit()
except backup_data.BackupError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # pragma: no cover - Schutznetz gegen halbe Zustände
db.rollback()
raise HTTPException(
status_code=400, detail=f"Wiederherstellung fehlgeschlagen: {exc}"
) from exc
if scope == "system":
# Die eigene Sitzung wurde mitgelöscht; alle übrigen ebenfalls beenden.
sessions.revoke_all_everywhere(db)
return {
"scope": scope,
"mode": mode,
"restored": bilanz,
"snapshot": os.path.basename(schnappschuss) if schnappschuss else None,
"logout_required": scope == "system",
}