Project-Image-Uploader/docs/FEATURE_PLAN-autogen-openapi.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

196 lines
6.5 KiB
Markdown

# Feature Plan: Autogenerierte OpenAPI / Swagger Spec + API Restructuring
**Branch:** `feature/autogen-openapi`
**Datum:** 16. November 2025
**Status:** ✅ Complete - Auto-generation active, Single Source of Truth established
## 🎯 Hauptziele
1.**OpenAPI Auto-Generation:** Swagger Spec wird automatisch aus Route-Definitionen generiert
2.**Konsistente API-Struktur:** Klare, REST-konforme API-Organisation für einfache KI-Navigation
3.**Single Source of Truth:** `routeMappings.js` als zentrale Route-Konfiguration
4.**Developer Experience:** Swagger UI unter `/api/docs` (dev-only)
5.**Test Coverage:** 45 automatisierte Tests, 100% passing
6.**API Security:** Bearer Token Authentication für Admin-Endpoints
---
## 📊 API-Struktur (Ziel)
### Design-Prinzipien
- **Prefix = Zugriffsebene:** Struktur basiert auf Authentifizierung/Autorisierung
- **REST-konform:** Standard HTTP Methoden (GET, POST, PUT, PATCH, DELETE)
- **KI-freundlich:** Klare Hierarchie, vorhersagbare Patterns
- **Konsistent:** Alle Routen folgen dem gleichen Muster
### Routing-Schema
```
/api/upload (öffentlich - Upload-Funktionen)
/api/groups (öffentlich - Slideshow-Anzeige)
/api/manage/:token/* (token-basiert - User-Verwaltung)
/api/admin/* (geschützt - Moderation)
/api/system/* (intern - Wartung)
```
### Detaillierte Endpunkte
#### 📤 Public API
```
POST /api/upload - Single file upload
POST /api/upload/batch - Batch upload
GET /api/groups - List approved slideshows
GET /api/groups/:groupId - View specific slideshow
```
#### 🔑 Management API
Token-basierter Zugriff für Slideshow-Ersteller:
```
GET /api/manage/:token - Get slideshow info
PUT /api/manage/:token/consents - Update consents
PUT /api/manage/:token/metadata - Update metadata
PUT /api/manage/:token/images/descriptions - Update image descriptions
POST /api/manage/:token/images - Add images
DELETE /api/manage/:token/images/:imageId - Delete image
DELETE /api/manage/:token - Delete slideshow
```
#### 👮 Admin API
Geschützte Moderation- und Management-Funktionen:
```
# Moderation
GET /api/admin/moderation/groups - List pending slideshows
GET /api/admin/moderation/groups/:id - Get slideshow details
PATCH /api/admin/groups/:id/approve - Approve slideshow
PATCH /api/admin/groups/:id - Edit slideshow
DELETE /api/admin/groups/:id/images/:imageId - Delete single image
PATCH /api/admin/groups/:id/images/batch-description
PUT /api/admin/groups/:id/reorder - Reorder images
# Logs & Monitoring
GET /api/admin/deletion-log - Recent deletions
GET /api/admin/deletion-log/stats - Deletion statistics
GET /api/admin/management-audit - Audit log
GET /api/admin/rate-limiter/stats - Rate limiter stats
# Cleanup
POST /api/admin/cleanup/trigger - Trigger cleanup
GET /api/admin/cleanup/preview - Preview cleanup targets
# Consents & Social Media
GET /api/admin/consents/export - Export consents (CSV)
GET /api/admin/social-media/platforms - List platforms
```
#### ⚙️ System API
Interne System-Operationen:
```
GET /api/system/migration/status - Migration status
POST /api/system/migration/migrate - Run migration
POST /api/system/migration/rollback - Rollback migration
GET /api/system/migration/health - Health check
```
---
## 🔧 Technische Implementierung
### Komponenten
- **swagger-autogen** (v6.2.8): OpenAPI 3.0 Generation
- **swagger-ui-express** (v4.6.3): Interactive API docs
- **Custom Generator:** `src/generate-openapi.js`
### Generator-Logik
```javascript
// Pro Router-Datei einzeln scannen + Mount-Prefix anwenden
for each routerMapping {
swaggerAutogen(tempFile, [routeFile], { basePath: prefix })
merge paths with prefix into final spec
}
```
### Single Source of Truth
1. **Router-Files (`src/routes/*.js`)**: Enthalten nur relative Pfade
2. **Mount-Konfiguration (`src/routes/index.js`)**: Definiert Prefixes
3. **OpenAPI Generation:** `generate-openapi.js` liest beide und merged
---
## 📚 Für KI-Nutzung
### API-Hierarchie verstehen
```
/api/* ← Alle API-Endpoints
├─ /upload, /groups ← Öffentlich
├─ /manage/:token/* ← Token-basiert
├─ /admin/* ← Geschützt
└─ /system/* ← Intern
```
### Neue Route hinzufügen
```bash
# 1. Route in passender Datei hinzufügen (z.B. admin.js)
router.get('/new-endpoint', ...)
# 2. In routeMappings.js registrieren (falls neue Datei)
{ router: 'newRoute', prefix: '/api/admin', file: 'newRoute.js' }
# 3. OpenAPI wird automatisch beim Backend-Start generiert
npm run dev
# 4. Tests schreiben: tests/api/newRoute.test.js
npm test
# 5. Swagger UI: http://localhost:5001/api/docs
```
---
## ✅ Implementierungsstatus (November 16, 2025)
### Completed Features
**Single Source of Truth**: `routeMappings.js` als zentrale Route-Konfiguration
**Auto-Generation**: OpenAPI-Spec automatisch beim Backend-Start
**Authentication**: Bearer Token für Admin-Endpoints
**Test Suite**: 45 automatisierte Tests (100% passing)
**Documentation**: `routes/README.md` + `AUTHENTICATION.md`
**Route Order Fix**: Express routing order documented & fixed
### Known Issues (Resolved)
**Express Route Order**: Consent router now mounted before admin router
**Test Permissions**: Tests use `/tmp/` for uploads
**SQLite Async**: Connection properly promisified
---
## ⏱️ Aufwandsschätzung (Final)
| Phase | Zeit | Status |
|-------|------|--------|
| MVP OpenAPI Generation | 2h | ✅ Done |
| API Restructuring | 8h | ✅ Done |
| Authentication System | 4h | ✅ Done |
| Test Suite | 6h | ✅ Done |
| Documentation | 2h | ✅ Done |
| **Total** | **22h** | **100%** |
---
## 🚀 Frontend Migration Guide
**Required Changes:**
1. **Add Bearer Token**: All `/api/admin/*` calls need `Authorization: Bearer <token>` header
2. **Verify Paths**: Check against `routeMappings.js` (consent: `/api/admin/groups/by-consent`)
3. **Handle 403**: Add error handling for missing authentication
4. **Environment**: Add `REACT_APP_ADMIN_API_KEY` to `.env`
**See `AUTHENTICATION.md` for complete setup guide**
---
**Erstellt:** 16. November 2025
**Aktualisiert:** 16. November 2025
**Status:** ✅ Production Ready