Project-Image-Uploader/frontend/MIGRATION-GUIDE.md
matthias.lotz 7cb264820e docs: Correct migration guide - ALL routes changed, not just admin
Critical corrections to frontend/MIGRATION-GUIDE.md:
- Emphasize ALL API routes now have consistent /api prefix
- Old routes had inconsistent prefixes (some with /api, some without)
- List specific files with wrong routes that need fixing:
  * ModerationGroupsPage.js: /groups/* → /api/admin/groups/*
  * ModerationGroupImagesPage.js: /moderation/groups/* → /api/admin/groups/*
  * PublicGroupImagesPage.js: /groups/* → /api/groups/*
- Add 3-phase checklist: Route Prefixes → Authentication → Testing
- Provide grep commands to find ALL fetch/axios calls
- Make clear this affects the entire frontend, not just admin features

Migration effort estimate increased: 3-4 hours (route audit + auth)
2025-11-16 18:25:32 +01:00

10 KiB
Raw Blame History

Frontend Migration Guide - API Umstrukturierung

Datum: 16. November 2025
Betrifft: ALLE API-Aufrufe im Frontend
Status: ⚠️ Aktion erforderlich - ALLE Routen prüfen!


<EFBFBD> BREAKING CHANGE: Konsistente /api Prefixes

ALLE API-Routen haben sich geändert!

Vorher (inkonsistent):

// Teils mit /api
fetch('/api/upload/batch')
fetch('/api/manage/xyz')

// Teils OHNE /api - FALSCH!
fetch('/groups/123')
fetch('/groups/123/approve')
fetch('/moderation/groups/123')

Jetzt (konsistent):

// ALLE Routen mit /api Prefix
fetch('/api/upload/batch')
fetch('/api/manage/xyz')
fetch('/api/groups/123')              // Public
fetch('/api/admin/groups/123/approve') // Admin
fetch('/api/admin/groups/123')        // Admin

🔒 Admin API Authentication

Alle Admin-Endpoints (/api/admin/* und /api/system/*) benötigen jetzt Bearer Token Authentication.

Route-Hierarchie

  1. Public API: /api/*

    • Öffentlich zugänglich
    • /api/upload, /api/groups, /api/download, etc.
  2. Management API: /api/manage/*

    • Token-basiert (UUID aus Upload-Response)
    • Für Gruppenbesitzer
  3. Admin API: /api/admin/* ⚠️ BEARER TOKEN ERFORDERLICH

    • Moderation, Logs, Consents
    • /api/admin/groups, /api/admin/deletion-log, etc.
  4. System API: /api/system/migration/* ⚠️ BEARER TOKEN ERFORDERLICH

    • Wartungsfunktionen

Betroffene Admin-Endpoints

  • /api/admin/groups - Gruppen auflisten
  • /api/admin/groups/:id - Gruppe abrufen
  • /api/admin/groups/:id/approve - Gruppe genehmigen
  • /api/admin/groups/:id - Gruppe löschen
  • /api/admin/groups/:id/images/:imageId - Bild löschen
  • /api/admin/groups/by-consent - Nach Consent filtern
  • /api/admin/consents/export - Consent-Export
  • /api/admin/social-media/platforms - Plattformen auflisten
  • /api/admin/reorder/:groupId/images - Bilder neu anordnen
  • /api/admin/deletion-log - Deletion Log
  • /api/admin/cleanup/* - Cleanup-Funktionen
  • /api/admin/rate-limiter/stats - Rate-Limiter-Statistiken
  • /api/admin/management-audit - Audit-Log

System-Endpoints:

  • /api/system/migration/migrate - Migration ausführen
  • /api/system/migration/rollback - Migration zurückrollen

📝 Erforderliche Änderungen

1. ALLE API-Routen prüfen und /api hinzufügen

Schritt 1: Finde alle API-Aufrufe im Frontend:

# Alle fetch/axios Aufrufe finden
grep -r "fetch\(" frontend/src/
grep -r "axios\." frontend/src/

Schritt 2: Prüfe jede Route und füge /api Prefix hinzu (falls fehlend):

// ❌ FALSCH (alte Routen)
fetch('/groups/123')
fetch('/groups/123/approve')
fetch('/moderation/groups/123')

// ✅ RICHTIG (neue Routen)
fetch('/api/groups/123')                    // Public
fetch('/api/admin/groups/123/approve')      // Admin (+ Bearer Token!)
fetch('/api/admin/groups/123')              // Admin (+ Bearer Token!)

2. Environment Variable für Admin Token hinzufügen

# frontend/.env oder frontend/.env.local
REACT_APP_ADMIN_API_KEY=your-secure-admin-token-here

Token generieren:

# Linux/Mac:
openssl rand -hex 32

# Node.js:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

⚠️ Wichtig: Gleiches Token in Backend .env als ADMIN_API_KEY eintragen!

3. API-Aufrufe für Admin-Endpoints anpassen

Vorher (ohne Auth):

const response = await fetch('/api/admin/groups');

Nachher (mit Bearer Token):

const response = await fetch('/api/admin/groups', {
  headers: {
    'Authorization': `Bearer ${process.env.REACT_APP_ADMIN_API_KEY}`,
    'Content-Type': 'application/json'
  }
});

3. Zentrale API-Helper-Funktion erstellen

Empfohlen: Erstelle eine zentrale Funktion für alle Admin-API-Calls:

// src/services/adminApiService.js
const ADMIN_API_KEY = process.env.REACT_APP_ADMIN_API_KEY;

export const adminFetch = async (url, options = {}) => {
  const defaultHeaders = {
    'Authorization': `Bearer ${ADMIN_API_KEY}`,
    'Content-Type': 'application/json'
  };

  const response = await fetch(url, {
    ...options,
    headers: {
      ...defaultHeaders,
      ...options.headers
    }
  });

  if (response.status === 403) {
    throw new Error('Authentication failed - Invalid or missing admin token');
  }

  return response;
};

// Verwendung:
import { adminFetch } from './services/adminApiService';

const response = await adminFetch('/api/admin/groups');
const data = await response.json();

4. Error Handling erweitern

try {
  const response = await adminFetch('/api/admin/groups');
  
  if (response.status === 403) {
    // Auth fehlt oder ungültig
    console.error('Admin authentication required');
    // Redirect zu Login oder Fehlermeldung anzeigen
  }
  
  if (response.status === 429) {
    // Rate Limit überschritten
    console.error('Too many requests');
  }
  
  const data = await response.json();
  // ...
} catch (error) {
  console.error('Admin API error:', error);
}

🔍 Betroffene Dateien finden

Alle API-Calls prüfen (KRITISCH!)

cd frontend/src

# ALLE API-Calls finden (fetch + axios):
grep -rn "fetch(" --include="*.js" --include="*.jsx"
grep -rn "axios\." --include="*.js" --include="*.jsx"

# Spezifisch nach alten Routen OHNE /api suchen:
grep -rn "fetch('/groups" --include="*.js"
grep -rn "fetch('/moderation" --include="*.js"

# Admin-API-Calls finden:
grep -rn "/api/admin" --include="*.js" --include="*.jsx"

Bekannte betroffene Dateien:

Routen ohne /api Prefix (MÜSSEN GEFIXT WERDEN):

  • Components/Pages/ModerationGroupsPage.js

    • /groups/${groupId}/approve /api/admin/groups/${groupId}/approve
    • /groups/${groupId} (DELETE) → /api/admin/groups/${groupId}
    • /api/social-media/platforms /api/admin/social-media/platforms
  • Components/Pages/ModerationGroupImagesPage.js

    • /moderation/groups/${groupId} /api/admin/groups/${groupId}
  • Components/Pages/PublicGroupImagesPage.js

    • /groups/${groupId} /api/groups/${groupId}

Admin-Endpoints (benötigen Bearer Token):

  • Components/Pages/ModerationGroupsPage.js - Alle Admin-Calls
  • Components/Pages/ModerationGroupImagesPage.js - Gruppe laden + Bilder löschen
  • Components/ComponentUtils/DeletionLogSection.js - Deletion Log
  • Components/ComponentUtils/ConsentManager.js - Consent Export (wenn Admin)
  • services/reorderService.js - Admin-Reorder (wenn vorhanden)

Public/Management Endpoints (nur Pfad prüfen):

  • Utils/batchUpload.js - Bereits korrekt (/api/...)
  • Components/Pages/ManagementPortalPage.js - Bereits korrekt (/api/manage/...)
  • Utils/sendRequest.js - Bereits korrekt (axios)

Checkliste

Phase 1: Route-Prefixes (ALLE Dateien)

  • Alle fetch() und axios Calls gefunden (grep)
  • Alle Routen ohne /api Prefix identifiziert
  • /api Prefix zu Public-Routen hinzugefügt (/api/groups, /api/upload)
  • Admin-Routen auf /api/admin/* geändert
  • Management-Routen auf /api/manage/* geprüft (sollten schon korrekt sein)

Phase 2: Admin Authentication

  • REACT_APP_ADMIN_API_KEY in .env hinzugefügt
  • Token im Backend als ADMIN_API_KEY konfiguriert
  • Zentrale adminFetch Funktion erstellt
  • Authorization Header zu ALLEN /api/admin/* Calls hinzugefügt
  • Authorization Header zu /api/system/* Calls hinzugefügt (falls vorhanden)
  • 403 Error Handling implementiert

Phase 3: Testing & Deployment

  • Frontend lokal getestet (alle Routen)
  • Admin-Funktionen getestet (Approve, Delete, etc.)
  • Public-Routen getestet (Gruppe laden, Upload)
  • Production .env aktualisiert

🧪 Testing

Lokales Testing

  1. Backend mit Admin-Key starten:

    cd backend
    echo "ADMIN_API_KEY=test-key-12345" >> .env
    npm run dev
    
  2. Frontend mit Admin-Key starten:

    cd frontend
    echo "REACT_APP_ADMIN_API_KEY=test-key-12345" >> .env.local
    npm start
    
  3. Moderation-Seite öffnen und Admin-Funktionen testen

Test-Fälle

  • Admin-Funktionen funktionieren mit gültigem Token
  • 403 Error bei fehlendem/falschem Token
  • Consent-Export funktioniert
  • Gruppen löschen funktioniert
  • Bilder neu anordnen funktioniert

📚 Weitere Dokumentation

  • Backend Auth-Doku: AUTHENTICATION.md
  • API Route-Übersicht: backend/src/routes/README.md
  • Route-Konfiguration: backend/src/routes/routeMappings.js
  • OpenAPI Spec: backend/docs/openapi.json
  • Swagger UI: http://localhost:5001/api/docs (dev only)

🆘 Troubleshooting

Problem: "403 Forbidden" Fehler

Ursachen:

  1. REACT_APP_ADMIN_API_KEY nicht gesetzt
  2. Token falsch konfiguriert (Frontend ≠ Backend)
  3. Token enthält Leerzeichen/Zeilenumbrüche

Lösung:

# Frontend .env prüfen:
cat frontend/.env | grep ADMIN_API_KEY

# Backend .env prüfen:
cat backend/.env | grep ADMIN_API_KEY

# Beide müssen identisch sein!

Problem: "ADMIN_API_KEY not configured" (500 Error)

Ursache: Backend hat ADMIN_API_KEY nicht in .env

Lösung:

cd backend
echo "ADMIN_API_KEY=$(openssl rand -hex 32)" >> .env

Problem: Token wird nicht gesendet

Prüfen in Browser DevTools:

  1. Network Tab öffnen
  2. Admin-API-Request auswählen
  3. "Headers" Tab prüfen
  4. Sollte enthalten: Authorization: Bearer <token>

Problem: CORS-Fehler

Ursache: Backend CORS-Middleware blockiert Authorization-Header

Lösung: Bereits implementiert in backend/src/middlewares/cors.js:

allowedHeaders: ['Content-Type', 'Authorization']

🚀 Deployment

Production Checklist

  • Sicheren Admin-Token generiert (min. 32 Bytes hex)
  • Token in Backend .env als ADMIN_API_KEY
  • Token in Frontend Build-Environment als REACT_APP_ADMIN_API_KEY
  • Token NICHT in Git committed (in .gitignore)
  • HTTPS verwendet (Token über unverschlüsselte HTTP ist unsicher)
  • Token-Rotation-Prozess dokumentiert
  • Backup des Tokens an sicherem Ort gespeichert

Docker Deployment

# docker-compose.yml
services:
  backend:
    environment:
      - ADMIN_API_KEY=${ADMIN_API_KEY}
  
  frontend:
    environment:
      - REACT_APP_ADMIN_API_KEY=${ADMIN_API_KEY}
# .env (nicht in Git!)
ADMIN_API_KEY=your-production-token-here

Fragen? Siehe AUTHENTICATION.md für detaillierte Backend-Dokumentation.

Status der Backend-Changes: Vollständig implementiert und getestet (45/45 Tests passing)