# 📊 Admin Dashboard Integration – 4 Optionen ## Übersicht Hier sind die Best Practices für die Integration eines Admin-Panels in die Flask-App: --- ## Option 1: Embedded Admin-Route (Empfohlen für Beta) **Am schnellsten & sichersten für Beta-Phase** ### Wie es funktioniert: - Admin-HTML wird direkt als Template serviert - Nur für Admin-Benutzer zugänglich (/admin) - Integriertes Logging-Dashboard - Keine separate App nötig ### Implementierung: **In `app.py` (nach den Error Handlers hinzufügen):** ```python @app.route("/admin", methods=["GET"]) @auth.login_required def admin_dashboard(): """Admin Dashboard - nur für Admins""" user = auth.current_user() if user not in ADMIN_USERS: log_access(user, "/admin", "GET", 403) return jsonify({"error": "Unauthorized"}), 403 log_access(user, "/admin", "GET") return render_template("admin.html", username=user) @app.route("/api/admin/logs", methods=["GET"]) @auth.login_required def get_admin_logs(): """Logs als JSON für Dashboard""" user = auth.current_user() if user not in ADMIN_USERS: return jsonify({"error": "Unauthorized"}), 403 logs = [] if os.path.exists(LOG_FILE): with open(LOG_FILE, "r") as f: logs = json.load(f) # Optional: Letzte 100 Logs return jsonify({"logs": logs[-100:]}), 200 @app.route("/api/admin/stats", methods=["GET"]) @auth.login_required def get_admin_stats(): """Statistiken für Dashboard""" user = auth.current_user() if user not in ADMIN_USERS: return jsonify({"error": "Unauthorized"}), 403 logs = [] if os.path.exists(LOG_FILE): with open(LOG_FILE, "r") as f: logs = json.load(f) # Statistiken berechnen total_requests = len(logs) unique_users = len(set(log["username"] for log in logs)) failed_logins = len([l for l in logs if l["status"] == 401]) return jsonify({ "total_requests": total_requests, "unique_users": unique_users, "failed_logins": failed_logins, "last_update": datetime.now().isoformat() }), 200 ``` **Neue Template-Datei: `templates/admin.html`** ```html Naue Admin Panel

🔐 Admin Panel

Angemeldet als: {{ username }}
Statistiken werden geladen...

📋 Access Logs

Zeitstempel Benutzer Endpoint Methode Status
Logs werden geladen...
``` ### Zugriff: - URL: `http://localhost:5000/admin` - Nur für Admin-Benutzer (403 Unauthorized für andere) - Automatische Log-Anzeige --- ## Option 2: Separate Admin-App (für später) **Wenn Admin-Features wachsen:** Erstelle eine separate `admin_app.py`: ```python from flask import Flask, render_template from flask_httpauth import HTTPBasicAuth admin = Flask(__name__, template_folder='admin_templates') auth_admin = HTTPBasicAuth() ADMIN_USERS = {"admin": "admin_secure_pwd_2026"} @auth_admin.verify_password def verify(username, password): if username in ADMIN_USERS and ADMIN_USERS[username] == password: return username return None @admin.route("/", methods=["GET"]) @auth_admin.login_required def dashboard(): return render_template("admin.html") if __name__ == "__main__": admin.run(port=5001, debug=False) # Anderer Port ``` Dann starten mit: `python admin_app.py` --- ## Option 3: Reverse Proxy Setup (Production) **Mit Nginx als Reverse Proxy:** ```nginx server { listen 80; server_name rollcalculator.naue.de; # Main App (Port 5000) location / { proxy_pass http://localhost:5000; proxy_set_header Host $host; proxy_set_header Authorization $http_authorization; } # Admin (gleiche Auth, aber separates Template) location /admin { proxy_pass http://localhost:5000/admin; proxy_set_header Host $host; proxy_set_header Authorization $http_authorization; } } ``` --- ## Option 4: Vue.js / React Admin UI (für erweiterte Features) Falls du später komplexere Admin-Features brauchst: ```javascript // static/js/admin-dashboard.js class AdminDashboard { constructor() { this.stats = null; this.logs = []; this.init(); } async init() { await this.loadStats(); await this.loadLogs(); this.setupAutoRefresh(); } async loadStats() { const res = await fetch('/api/admin/stats'); this.stats = await res.json(); this.renderStats(); } async loadLogs() { const res = await fetch('/api/admin/logs'); this.logs = (await res.json()).logs; this.renderLogs(); } renderStats() { // Render logic... } renderLogs() { // Render logic... } setupAutoRefresh() { setInterval(() => this.loadStats(), 30000); setInterval(() => this.loadLogs(), 30000); } } // Starten new AdminDashboard(); ``` --- ## 🎯 Empfehlungen | Phase | Option | Vorteile | Nachteile | |-------|--------|----------|-----------| | **Beta** | Option 1 (Embedded) | ✅ Schnell, ✅ Sicher, ✅ Integriert | ⚠️ Einfaches UI | | **Production Beta** | Option 1 + Option 3 | ✅ Mit HTTPS, ✅ Skalierbar | ⚠️ Nginx-Setup | | **Später erweitern** | Option 4 (Vue/React) | ✅ Modern, ✅ Interactive | ⚠️ Komplexer | | **Separate Team** | Option 2 (Separate App) | ✅ Unabhängig, ✅ Unterschiedliche Tech Stack | ⚠️ 2 Apps | --- ## ⚡ Quick Start: Option 1 implementieren 1. **Kopiere den Code oben in `app.py`** (die neuen Routes) 2. **Erstelle `templates/admin.html`** mit dem HTML oben 3. **Starte Flask neu**: `python app.py` 4. **Öffne**: `http://localhost:5000/admin` 5. **Login**: admin / admin_secure_pwd_2026 --- ## Nächste Schritte - [ ] admin.html als Template in templates/ speichern - [ ] Routes in app.py hinzufügen - [ ] Tests mit Admin-User durchführen - [ ] Logs überprüfen - [ ] Optional: Charts/Graphs hinzufügen (Chart.js)