Project-Image-Uploader/frontend/MIGRATION-GUIDE.md
matthias.lotz cdb2aa95e6 feat: Add comprehensive test suite and admin API authentication
🧪 Testing Infrastructure (45 tests, 100% passing)
- Implemented Jest + Supertest framework for automated testing
- Unit tests: 5 tests for auth middleware (100% coverage)
- Integration tests: 40 tests covering admin, consent, migration, upload APIs
- Test execution time: ~10 seconds for full suite
- Coverage: 26% statements, 15% branches (realistic start)
- In-memory SQLite database for isolated testing
- Singleton server pattern for fast test execution
- Automatic cleanup and teardown

🔒 Admin API Authentication
- Bearer token authentication for all admin endpoints
- requireAdminAuth middleware with ADMIN_API_KEY validation
- Protected routes: /api/admin/*, /api/system/migration/migrate|rollback
- Complete authentication guide in AUTHENTICATION.md
- HTTP 403 for missing/invalid tokens, 500 if not configured
- Ready for production with token rotation support

📋 API Route Documentation
- Single Source of Truth: backend/src/routes/routeMappings.js
- Comprehensive route overview in backend/src/routes/README.md
- Express routing order documented (specific before generic)
- Frontend integration guide with authentication examples
- OpenAPI auto-generation integrated

🐛 Bug Fixes
- Fixed SQLite connection not properly awaited (caused test hangs)
- Fixed upload validation checking req.files.file before req.files
- Fixed Express route order (consent before admin router)
- Fixed test environment using /tmp for uploads (permission issues)

📚 Documentation Updates
- Updated README.md with testing and authentication features
- Updated README.dev.md with testing section and API development guide
- Updated CHANGELOG.md with complete feature documentation
- Updated FEATURE_PLAN-autogen-openapi.md (status: 100% complete)
- Added frontend/MIGRATION-GUIDE.md for frontend team

🚀 Frontend Impact
Frontend needs to add Bearer token to all /api/admin/* calls.
See frontend/MIGRATION-GUIDE.md for detailed instructions.

Test Status:  45/45 passing (100%)
Backend:  Production ready
Frontend: ⚠️ Migration required (see MIGRATION-GUIDE.md)
2025-11-16 18:08:48 +01:00

7.0 KiB

Frontend Migration Guide - Admin API Authentication

Datum: 16. November 2025
Betrifft: Alle Admin-API-Aufrufe im Frontend
Status: ⚠️ Aktion erforderlich


🔒 Was hat sich geändert?

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

Betroffene 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. Environment Variable 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!

2. API-Aufrufe 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

Such nach allen Admin-API-Aufrufen:

cd frontend/src

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

# Alle Fetch-Calls in spezifischen Komponenten:
grep -r "fetch.*admin" Components/Pages/

Wahrscheinlich betroffene Komponenten:

  • Components/Pages/ModerationGroupsPage.js
  • Components/Pages/ModerationGroupImagesPage.js
  • Components/ComponentUtils/ConsentManager.js (wenn im moderate-Modus)
  • services/reorderService.js (Admin-Reorder)
  • Jede andere Komponente, die Admin-Funktionen aufruft

Checkliste

  • REACT_APP_ADMIN_API_KEY in .env hinzugefügt
  • Token im Backend als ADMIN_API_KEY konfiguriert
  • Zentrale adminFetch Funktion erstellt
  • Alle Admin-API-Calls gefunden (grep)
  • Authorization Header zu allen Admin-Calls hinzugefügt
  • 403 Error Handling implementiert
  • Frontend lokal getestet
  • 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)