added login screen and admin console

This commit is contained in:
2026-05-28 15:40:26 +02:00
parent e267b1fe02
commit 5c4b944d6a
5 changed files with 1548 additions and 0 deletions
+479
View File
@@ -0,0 +1,479 @@
# 📊 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
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Naue Admin Panel</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Arial, sans-serif;
background: #f4f6f9;
color: #333;
}
.admin-header {
background: linear-gradient(135deg, #003366 0%, #0066cc 100%);
color: white;
padding: 20px 32px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
display: flex;
justify-content: space-between;
align-items: center;
}
.admin-header h1 { font-size: 24px; }
.admin-header .user-info {
font-size: 12px;
opacity: 0.9;
}
.admin-container {
max-width: 1200px;
margin: 30px auto;
padding: 0 20px 60px;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.07);
border-left: 4px solid #0066cc;
}
.stat-card .label {
font-size: 12px;
color: #666;
text-transform: uppercase;
margin-bottom: 8px;
}
.stat-card .value {
font-size: 32px;
font-weight: 700;
color: #0066cc;
}
.logs-section {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.07);
}
.logs-section h2 {
font-size: 18px;
margin-bottom: 20px;
color: #003366;
}
.logs-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.logs-table thead {
background: #f0f4fa;
border-bottom: 2px solid #0066cc;
}
.logs-table th {
padding: 12px;
text-align: left;
font-weight: 600;
color: #333;
}
.logs-table td {
padding: 10px 12px;
border-bottom: 1px solid #e8ecf0;
}
.logs-table tbody tr:hover {
background: #f8f9fa;
}
.status-200 { color: #28a745; font-weight: 600; }
.status-401 { color: #dc3545; font-weight: 600; }
.status-403 { color: #f0b429; font-weight: 600; }
.btn-refresh {
background: #0066cc;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-weight: 600;
margin-bottom: 20px;
}
.btn-refresh:hover { background: #0052a3; }
.loading {
text-align: center;
padding: 40px;
color: #666;
}
.footer {
text-align: center;
font-size: 11px;
color: #aaa;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #e8ecf0;
}
</style>
</head>
<body>
<div class="admin-header">
<div>
<h1>🔐 Admin Panel</h1>
<div class="user-info">Roll Calculator – Naue</div>
</div>
<div class="user-info">
Angemeldet als: <strong>{{ username }}</strong>
</div>
</div>
<div class="admin-container">
<!-- Statistics -->
<div class="stats-grid" id="statsGrid">
<div class="loading">Statistiken werden geladen...</div>
</div>
<!-- Logs Section -->
<div class="logs-section">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>📋 Access Logs</h2>
<button class="btn-refresh" onclick="refreshData()">🔄 Aktualisieren</button>
</div>
<table class="logs-table" id="logsTable">
<thead>
<tr>
<th>Zeitstempel</th>
<th>Benutzer</th>
<th>Endpoint</th>
<th>Methode</th>
<th>Status</th>
</tr>
</thead>
<tbody id="logsList">
<tr>
<td colspan="5" class="loading">Logs werden geladen...</td>
</tr>
</tbody>
</table>
</div>
<div class="footer">
Naue GmbH & Co. KG · Roll Calculator Admin Panel
</div>
</div>
<script>
async function refreshData() {
try {
// Fetch Statistics
const statsRes = await fetch('/api/admin/stats');
const stats = await statsRes.json();
// Fetch Logs
const logsRes = await fetch('/api/admin/logs');
const logsData = await logsRes.json();
// Display Statistics
const statsHtml = `
<div class="stat-card">
<div class="label">Gesamte Anfragen</div>
<div class="value">${stats.total_requests}</div>
</div>
<div class="stat-card">
<div class="label">Eindeutige Benutzer</div>
<div class="value">${stats.unique_users}</div>
</div>
<div class="stat-card">
<div class="label">Fehlgeschlagene Logins</div>
<div class="value" style="color: #dc3545;">${stats.failed_logins}</div>
</div>
`;
document.getElementById('statsGrid').innerHTML = statsHtml;
// Display Logs
const logsHtml = logsData.logs.reverse().map(log => {
const time = new Date(log.timestamp).toLocaleString('de-DE');
const statusClass = `status-${log.status}`;
return `
<tr>
<td>${time}</td>
<td>${log.username}</td>
<td>${log.endpoint}</td>
<td>${log.method}</td>
<td class="${statusClass}">${log.status}</td>
</tr>
`;
}).join('');
document.getElementById('logsList').innerHTML = logsHtml ||
'<tr><td colspan="5" style="text-align: center; padding: 20px;">Keine Logs verfügbar</td></tr>';
} catch (error) {
console.error('Fehler beim Laden der Daten:', error);
document.getElementById('logsList').innerHTML =
'<tr><td colspan="5" style="color: #dc3545;">Fehler beim Laden der Daten</td></tr>';
}
}
// Initial load
document.addEventListener('DOMContentLoaded', refreshData);
// Auto-refresh alle 30 Sekunden
setInterval(refreshData, 30000);
</script>
</body>
</html>
```
### 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)
@@ -0,0 +1,215 @@
# 🔧 Admin Panel Integration – Schritt-für-Schritt
## 1. Templates-Datei erstellen
Kopiere `admin.html` in dein `templates/` Verzeichnis:
```bash
cp admin.html templates/admin.html
```
## 2. Flask Routes hinzufügen
Öffne `app.py` und füge die neuen Routes hinzu:
**Nach den Error Handlers (ca. Zeile 80), vor `if __name__ == "__main__"`, hinzufügen:**
```python
# ============================================================================
# ADMIN ROUTES
# ============================================================================
@app.route("/admin", methods=["GET"])
@auth.login_required
def admin_dashboard():
"""Admin Dashboard - nur für Admin-Benutzer"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/admin", "GET", 403)
return jsonify({"error": "Unauthorized - Admin access required"}), 403
log_access(user, "/admin", "GET")
return render_template("admin.html")
@app.route("/api/admin/stats", methods=["GET"])
@auth.login_required
def get_admin_stats():
"""Statistiken für Admin Dashboard"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/api/admin/stats", "GET", 403)
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/stats", "GET")
logs = []
if os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r") as f:
logs = json.load(f)
except json.JSONDecodeError:
logs = []
total_requests = len(logs)
unique_users = len(set(log.get("username", "unknown") for log in logs))
failed_logins = len([l for l in logs if l.get("status") == 401])
return jsonify({
"total_requests": total_requests,
"unique_users": unique_users,
"failed_logins": failed_logins,
"timestamp": datetime.now().isoformat()
}), 200
@app.route("/api/admin/logs", methods=["GET"])
@auth.login_required
def get_admin_logs():
"""Access Logs für Admin Dashboard"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/api/admin/logs", "GET", 403)
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/logs", "GET")
logs = []
if os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r") as f:
logs = json.load(f)
except json.JSONDecodeError:
logs = []
logs_sorted = sorted(logs, key=lambda x: x.get("timestamp", ""), reverse=True)
return jsonify({"logs": logs_sorted[-500:]}), 200
```
## 3. Server testen
```bash
python app.py
```
## 4. Zugriff
- URL: **http://localhost:5000/admin**
- Login: **admin** / **admin_secure_pwd_2026**
---
## Features im Admin Panel
### 📊 Dashboard-Statistiken
- ✅ Gesamte API-Anfragen
- ✅ Eindeutige Benutzer
- ✅ Fehlgeschlagene Logins (401 Unauthorized)
### 📋 Access Logs
- ✅ Echtzeit-Logs mit Timestamp
- ✅ Benutzer, Endpoint, HTTP-Method, Status
- ✅ Farbcodierung nach HTTP-Status (200, 401, 403)
### 🔍 Filter & Suche
- ✅ Nach Benutzer filtern
- ✅ Nach Endpoint filtern
- ✅ Live-Filter während Eingabe
### ⬇️ Export
- ✅ Download als JSON
- ✅ Optionale CSV-Export
### 🔄 Auto-Refresh
- ✅ Automatische Aktualisierung alle 30 Sekunden
- ✅ Manueller Refresh-Button
---
## Sicherheit
### ✅ Implementiert:
- HTTP Basic Auth
- Admin-only Access (403 Unauthorized für Non-Admins)
- Audit-Logging aller Admin-Aktionen
- XSS-Protection (HTML-escaped)
### ⚠️ Für Production:
- HTTPS erforderlich (Basic Auth unsicher über HTTP!)
- Admin-Passwort ändern
- Logs regelmäßig archivieren
---
## Erweiterungen (Optional)
### Charts hinzufügen (Chart.js)
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="requestsChart"></canvas>
<script>
const ctx = document.getElementById('requestsChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
datasets: [{
label: 'Requests',
data: [12, 19, 3, 5, 2, 3, 7]
}]
}
});
</script>
```
### Weitere Admin-Features
- User-Management (neue Benutzer hinzufügen)
- Konfiguration Editor
- System-Monitor (CPU, RAM)
- Backup-Manager
- Audit-Trail Export
---
## Troubleshooting
### "403 Unauthorized" beim Öffnen von /admin
✓ Du musst als Admin angemeldet sein
✓ Login mit: `admin` / `admin_secure_pwd_2026`
### "No JSON object could be decoded" (in access_log.json)
✓ Lösche `access_log.json` und starte neu
✓ Die Datei wird automatisch neu erstellt
### Logs werden nicht angezeigt
✓ Prüfe, ob `access_log.json` im Projektverzeichnis existiert
✓ Öffne Browser Console (F12) auf Fehler
---
## API-Referenz
| Endpoint | Method | Auth | Beschreibung |
|----------|--------|------|-------------|
| `/admin` | GET | Admin | Admin-Dashboard |
| `/api/admin/stats` | GET | Admin | Statistiken (JSON) |
| `/api/admin/logs` | GET | Admin | Access-Logs (JSON) |
| `/api/admin/export` | GET | Admin | Export als JSON/CSV |
| `/api/admin/clear-logs` | POST | Admin | Alle Logs löschen |
---
## Nächste Schritte
- [ ] `admin.html` in `templates/` speichern
- [ ] Routes in `app.py` hinzufügen
- [ ] Server neustarten
- [ ] http://localhost:5000/admin testen
- [ ] Mit Admin-Credentials anmelden
- [ ] Logs prüfen
---
**Fertig!** 🎉 Dein Admin-Panel ist jetzt integriert!
+568
View File
@@ -0,0 +1,568 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0066cc">
<title>Admin Panel – Roll Calculator</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Segoe UI', Arial, sans-serif;
background: #f4f6f9;
color: #333;
min-height: 100vh;
}
/* ---- HEADER ---- */
.admin-header {
background: linear-gradient(135deg, #003366 0%, #0066cc 100%);
color: white;
padding: 20px 32px;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
display: flex;
justify-content: space-between;
align-items: center;
}
.admin-header h1 {
font-size: 24px;
font-weight: 700;
letter-spacing: 0.5px;
}
.admin-header .subtitle {
font-size: 12px;
opacity: 0.85;
}
.admin-header .user-info {
font-size: 12px;
opacity: 0.9;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
}
.admin-header .user-info strong {
opacity: 1;
font-weight: 600;
}
/* ---- CONTAINER ---- */
.admin-container {
max-width: 1300px;
margin: 30px auto;
padding: 0 20px 60px;
}
/* ---- STATS GRID ---- */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.stat-card {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 2px 8px rgba(0,0,0,0.07);
border-left: 4px solid #0066cc;
transition: transform 0.2s, box-shadow 0.2s;
}
.stat-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.stat-card.warning {
border-left-color: #f0b429;
}
.stat-card.danger {
border-left-color: #dc3545;
}
.stat-card .label {
font-size: 12px;
color: #666;
text-transform: uppercase;
letter-spacing: 0.4px;
margin-bottom: 8px;
font-weight: 600;
}
.stat-card .value {
font-size: 36px;
font-weight: 700;
color: #0066cc;
line-height: 1;
}
.stat-card.warning .value {
color: #f0b429;
}
.stat-card.danger .value {
color: #dc3545;
}
.stat-card .sublabel {
font-size: 11px;
color: #999;
margin-top: 8px;
}
/* ---- LOGS SECTION ---- */
.logs-section {
background: white;
border-radius: 10px;
padding: 24px;
box-shadow: 0 2px 8px rgba(0,0,0,0.07);
}
.logs-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
gap: 12px;
}
.logs-header h2 {
font-size: 18px;
color: #003366;
font-weight: 700;
}
.controls {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn {
background: #0066cc;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-weight: 600;
font-size: 13px;
transition: background 0.2s;
display: flex;
align-items: center;
gap: 6px;
}
.btn:hover {
background: #0052a3;
}
.btn.secondary {
background: #e0e0e0;
color: #333;
}
.btn.secondary:hover {
background: #d0d0d0;
}
.btn-refresh {
animation: spin 1s linear infinite;
}
.btn-refresh.spinning {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
/* ---- TABLE ---- */
.logs-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.logs-table thead {
background: #f0f4fa;
border-bottom: 2px solid #0066cc;
}
.logs-table th {
padding: 12px;
text-align: left;
font-weight: 600;
color: #333;
}
.logs-table td {
padding: 10px 12px;
border-bottom: 1px solid #e8ecf0;
}
.logs-table tbody tr {
transition: background 0.15s;
}
.logs-table tbody tr:hover {
background: #f8f9fa;
}
.status-200 {
color: #28a745;
font-weight: 600;
background: #f0f9f6;
padding: 2px 6px;
border-radius: 3px;
display: inline-block;
}
.status-401 {
color: #dc3545;
font-weight: 600;
background: #fff0f0;
padding: 2px 6px;
border-radius: 3px;
display: inline-block;
}
.status-403 {
color: #f0b429;
font-weight: 600;
background: #fffbea;
padding: 2px 6px;
border-radius: 3px;
display: inline-block;
}
/* ---- LOADING / EMPTY ---- */
.loading {
text-align: center;
padding: 40px;
color: #999;
}
.empty {
text-align: center;
padding: 40px;
color: #999;
font-style: italic;
}
.error {
background: #fff0f0;
color: #dc3545;
padding: 12px;
border-radius: 5px;
border-left: 4px solid #dc3545;
margin: 12px 0;
}
/* ---- FILTERS ---- */
.filters {
display: flex;
gap: 10px;
margin-bottom: 20px;
flex-wrap: wrap;
}
.filter-input {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 13px;
}
.filter-input:focus {
outline: none;
border-color: #0066cc;
box-shadow: 0 0 0 2px rgba(0,102,204,0.1);
}
/* ---- FOOTER ---- */
.admin-footer {
text-align: center;
font-size: 11px;
color: #aaa;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #e8ecf0;
}
/* ---- RESPONSIVE ---- */
@media (max-width: 768px) {
.admin-header {
flex-direction: column;
gap: 12px;
align-items: flex-start;
}
.admin-header .user-info {
align-items: flex-start;
}
.stats-grid {
grid-template-columns: 1fr;
}
.logs-header {
flex-direction: column;
align-items: flex-start;
}
.controls {
width: 100%;
}
.btn {
flex: 1;
justify-content: center;
}
.logs-table {
font-size: 12px;
}
.logs-table th, .logs-table td {
padding: 8px;
}
}
</style>
</head>
<body>
<!-- HEADER -->
<div class="admin-header">
<div>
<h1>🔐 Admin Panel</h1>
<div class="subtitle">Roll Calculator – Naue GmbH & Co. KG</div>
</div>
<div class="user-info">
<span>Angemeldet als:</span>
<strong id="authUser">admin</strong>
</div>
</div>
<!-- MAIN CONTAINER -->
<div class="admin-container">
<!-- STATISTICS -->
<div class="stats-grid" id="statsGrid">
<div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #999;">
⏳ Statistiken werden geladen...
</div>
</div>
<!-- LOGS SECTION -->
<div class="logs-section">
<!-- HEADER -->
<div class="logs-header">
<h2>📋 Access Logs</h2>
<div class="controls">
<button class="btn" id="refreshBtn" onclick="refreshData()">
<span id="refreshIcon">🔄</span> Aktualisieren
</button>
<button class="btn secondary" onclick="downloadLogs()">
⬇️ Download
</button>
</div>
</div>
<!-- FILTERS -->
<div class="filters">
<input
type="text"
class="filter-input"
placeholder="Nach Benutzer filtern..."
id="filterUser"
onkeyup="filterLogs()"
>
<input
type="text"
class="filter-input"
placeholder="Nach Endpoint filtern..."
id="filterEndpoint"
onkeyup="filterLogs()"
>
</div>
<!-- TABLE -->
<div id="errorContainer"></div>
<table class="logs-table">
<thead>
<tr>
<th>Zeitstempel</th>
<th>Benutzer</th>
<th>Endpoint</th>
<th>Methode</th>
<th style="width: 80px;">Status</th>
</tr>
</thead>
<tbody id="logsList">
<tr>
<td colspan="5" class="loading">Logs werden geladen...</td>
</tr>
</tbody>
</table>
</div>
<!-- FOOTER -->
<div class="admin-footer">
ℹ️ Logs werden automatisch alle 30 Sekunden aktualisiert |
Letztes Update: <span id="lastUpdate">-</span>
</div>
</div>
<!-- SCRIPTS -->
<script>
let allLogs = [];
// Get authenticated user from API
async function getAuthUser() {
try {
const res = await fetch('/api/user');
const data = await res.json();
document.getElementById('authUser').textContent = data.username || 'admin';
} catch (e) {
console.warn('Konnte Benutzerinformation nicht laden');
}
}
// Refresh Data (Statistiken + Logs)
async function refreshData() {
const btn = document.getElementById('refreshBtn');
const icon = document.getElementById('refreshIcon');
try {
icon.style.animation = 'spin 1s linear infinite';
// Load Statistics
const statsRes = await fetch('/api/admin/stats');
if (!statsRes.ok) throw new Error('Statistiken konnten nicht geladen werden');
const stats = await statsRes.json();
// Load Logs
const logsRes = await fetch('/api/admin/logs');
if (!logsRes.ok) throw new Error('Logs konnten nicht geladen werden');
const logsData = await logsRes.json();
allLogs = logsData.logs || [];
// Render Statistics
renderStats(stats);
// Render Logs
renderLogs(allLogs);
// Update timestamp
document.getElementById('lastUpdate').textContent = new Date().toLocaleTimeString('de-DE');
// Clear error
document.getElementById('errorContainer').innerHTML = '';
} catch (error) {
console.error('Fehler beim Laden der Daten:', error);
document.getElementById('errorContainer').innerHTML =
'<div class="error">❌ ' + error.message + '</div>';
} finally {
icon.style.animation = 'none';
}
}
// Render Statistics
function renderStats(stats) {
const html = `
<div class="stat-card">
<div class="label">📊 Gesamte Anfragen</div>
<div class="value">${stats.total_requests || 0}</div>
</div>
<div class="stat-card">
<div class="label">👥 Eindeutige Benutzer</div>
<div class="value">${stats.unique_users || 0}</div>
</div>
<div class="stat-card danger">
<div class="label">⛔ Fehlgeschlagene Logins</div>
<div class="value">${stats.failed_logins || 0}</div>
</div>
`;
document.getElementById('statsGrid').innerHTML = html;
}
// Render Logs
function renderLogs(logs) {
if (!logs || logs.length === 0) {
document.getElementById('logsList').innerHTML =
'<tr><td colspan="5" class="empty">Keine Logs verfügbar</td></tr>';
return;
}
const html = logs.reverse().map(log => {
const time = new Date(log.timestamp).toLocaleString('de-DE');
const statusClass = `status-${log.status}`;
return `
<tr>
<td>${time}</td>
<td><strong>${log.username}</strong></td>
<td><code>${log.endpoint}</code></td>
<td>${log.method}</td>
<td><span class="${statusClass}">${log.status}</span></td>
</tr>
`;
}).join('');
document.getElementById('logsList').innerHTML = html;
}
// Filter Logs
function filterLogs() {
const userFilter = document.getElementById('filterUser').value.toLowerCase();
const endpointFilter = document.getElementById('filterEndpoint').value.toLowerCase();
const filtered = allLogs.filter(log =>
log.username.toLowerCase().includes(userFilter) &&
log.endpoint.toLowerCase().includes(endpointFilter)
);
renderLogs(filtered);
}
// Download Logs as JSON
function downloadLogs() {
const data = JSON.stringify(allLogs, null, 2);
const blob = new Blob([data], { type: 'application/json' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `access-logs-${new Date().toISOString()}.json`;
a.click();
window.URL.revokeObjectURL(url);
}
// Initialize
document.addEventListener('DOMContentLoaded', () => {
getAuthUser();
refreshData();
// Auto-refresh every 30 seconds
setInterval(refreshData, 30000);
});
</script>
</body>
</html>
+179
View File
@@ -0,0 +1,179 @@
"""
ADMIN ROUTES FÜR app.py
Diese Routes sollten zu app.py hinzugefügt werden (nach den Error Handlers, vor if __name__)
"""
# ============================================================================
# ADMIN ROUTES (diese zeilen in app.py hinzufügen!)
# ============================================================================
@app.route("/admin", methods=["GET"])
@auth.login_required
def admin_dashboard():
"""Admin Dashboard - nur für Admin-Benutzer"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/admin", "GET", 403)
return jsonify({"error": "Unauthorized - Admin access required"}), 403
log_access(user, "/admin", "GET")
return render_template("admin.html")
@app.route("/api/admin/stats", methods=["GET"])
@auth.login_required
def get_admin_stats():
"""Statistiken für Admin Dashboard"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/api/admin/stats", "GET", 403)
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/stats", "GET")
logs = []
if os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r") as f:
logs = json.load(f)
except json.JSONDecodeError:
logs = []
# Berechne Statistiken
total_requests = len(logs)
unique_users = len(set(log.get("username", "unknown") for log in logs))
failed_logins = len([l for l in logs if l.get("status") == 401])
return jsonify({
"total_requests": total_requests,
"unique_users": unique_users,
"failed_logins": failed_logins,
"timestamp": datetime.now().isoformat()
}), 200
@app.route("/api/admin/logs", methods=["GET"])
@auth.login_required
def get_admin_logs():
"""Access Logs für Admin Dashboard"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/api/admin/logs", "GET", 403)
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/logs", "GET")
logs = []
if os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r") as f:
logs = json.load(f)
except json.JSONDecodeError:
logs = []
# Sortiere nach Zeitstempel absteigend (neueste zuerst)
logs_sorted = sorted(logs, key=lambda x: x.get("timestamp", ""), reverse=True)
# Optionales Limit (letzte 500 Logs)
return jsonify({"logs": logs_sorted[-500:]}), 200
@app.route("/api/admin/export", methods=["GET"])
@auth.login_required
def export_logs():
"""Exportiere Logs als CSV/JSON"""
user = auth.current_user()
if user not in ADMIN_USERS:
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/export", "GET")
logs = []
if os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "r") as f:
logs = json.load(f)
except json.JSONDecodeError:
logs = []
# Optional: Als CSV exportieren
fmt = request.args.get("format", "json")
if fmt == "csv":
import csv
from io import StringIO
output = StringIO()
writer = csv.DictWriter(output, fieldnames=["timestamp", "username", "endpoint", "method", "status"])
writer.writeheader()
writer.writerows(logs)
response = app.make_response(output.getvalue())
response.headers["Content-Disposition"] = f"attachment; filename=logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
response.headers["Content-Type"] = "text/csv"
return response
else:
response = app.make_response(json.dumps(logs, indent=2))
response.headers["Content-Disposition"] = f"attachment; filename=logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
response.headers["Content-Type"] = "application/json"
return response
# ============================================================================
# OPTIONAL: Admin-Utility-Routes
# ============================================================================
@app.route("/api/admin/clear-logs", methods=["POST"])
@auth.login_required
def clear_logs():
"""Lösche alle Logs (nur für Admin, mit Bestätigung)"""
user = auth.current_user()
if user not in ADMIN_USERS:
return jsonify({"error": "Unauthorized"}), 403
# Safety: Verlange "confirm=true" Query Parameter
confirm = request.args.get("confirm") == "true"
if not confirm:
return jsonify({"error": "Confirmation required (add ?confirm=true)"}), 400
log_access(user, "/api/admin/clear-logs", "POST")
# Backup erstellen vor dem Löschen
if os.path.exists(LOG_FILE):
backup_file = LOG_FILE + f".backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
import shutil
shutil.copy(LOG_FILE, backup_file)
# Logs leeren
with open(LOG_FILE, "w") as f:
json.dump([], f)
return jsonify({
"status": "success",
"message": "Alle Logs wurden gelöscht (Backup erstellt)"
}), 200
@app.route("/api/admin/system-info", methods=["GET"])
@auth.login_required
def get_system_info():
"""System-Information für Admin"""
user = auth.current_user()
if user not in ADMIN_USERS:
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/api/admin/system-info", "GET")
import psutil
return jsonify({
"environment": os.getenv("FLASK_ENV", "production"),
"debug_mode": app.debug,
"database_file": LOG_FILE,
"database_size_kb": os.path.getsize(LOG_FILE) / 1024 if os.path.exists(LOG_FILE) else 0,
"timestamp": datetime.now().isoformat(),
# Optional: CPU/RAM Info
# "cpu_percent": psutil.cpu_percent(),
# "memory_percent": psutil.virtual_memory().percent,
}), 200
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""
Automatischer Fix für article-data.json Fetch-URLs in Flask
Ersetzt relative URLs durch /static/ URLs
"""
import re
import os
from pathlib import Path
def fix_html_file(html_path):
"""Ersetzt die alten Fetch-URLs durch die neuen Flask-URLs"""
if not os.path.exists(html_path):
print(f"❌ Datei nicht gefunden: {html_path}")
return False
print(f"📖 Öffne: {html_path}")
with open(html_path, 'r', encoding='utf-8') as f:
content = f.read()
original_content = content
changes = []
# Fix 1: fetch('article-data.json') → fetch('/static/article-data.json')
if "fetch('article-data.json')" in content or 'fetch("article-data.json")' in content:
content = content.replace("fetch('article-data.json')", "fetch('/static/article-data.json')")
content = content.replace('fetch("article-data.json")', 'fetch("/static/article-data.json")')
changes.append("✓ article-data.json URL aktualisiert")
# Fix 2: fetch('config.json') → fetch('/static/config.json')
if "fetch('config.json')" in content or 'fetch("config.json")' in content:
content = content.replace("fetch('config.json')", "fetch('/static/config.json')")
content = content.replace('fetch("config.json")', 'fetch("/static/config.json")')
changes.append("✓ config.json URL aktualisiert")
# Fix 3: register('service-worker.js') → register('/static/service-worker.js')
if "register('service-worker.js')" in content or 'register("service-worker.js")' in content:
content = content.replace("register('service-worker.js')", "register('/static/service-worker.js')")
content = content.replace('register("service-worker.js")', 'register("/static/service-worker.js")')
changes.append("✓ service-worker.js URL aktualisiert")
if content != original_content:
# Backup erstellen
backup_path = html_path + ".backup"
with open(backup_path, 'w', encoding='utf-8') as f:
f.write(original_content)
print(f"💾 Backup erstellt: {backup_path}")
# Neue Version speichern
with open(html_path, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✅ HTML aktualisiert: {html_path}")
for change in changes:
print(f" {change}")
return True
else:
print("⚠️ Keine Änderungen notwendig (URLs sind bereits korrekt)")
return False
def check_static_files():
"""Prüft ob die benötigten Dateien im static/ Ordner sind"""
print("\n🔍 Prüfe static/ Verzeichnis...")
files_to_check = ['article-data.json', 'config.json']
found = []
missing = []
for filename in files_to_check:
path = os.path.join('static', filename)
if os.path.exists(path):
size = os.path.getsize(path)
found.append(f" ✓ {filename} ({size} bytes)")
else:
missing.append(f" ❌ {filename} (NICHT GEFUNDEN)")
for msg in found:
print(msg)
for msg in missing:
print(msg)
return len(missing) == 0
if __name__ == "__main__":
print("=" * 60)
print("Fix für article-data.json Flask-URLs")
print("=" * 60)
html_file = "templates/roll_calculator.html"
success = fix_html_file(html_file)
files_ok = check_static_files()
print("\n" + "=" * 60)
if success or files_ok:
print("✅ Fix abgeschlossen!")
print("\n📝 Nächste Schritte:")
print(" 1. Browser neuladen (Ctrl+Shift+R)")
print(" 2. Öffne Browser Console (F12)")
print(" 3. Du solltest sehen:")
print(" 'Article data loaded: XXX items'")
print(" 'Config updated from file'")
else:
print("⚠️ Keine Änderungen nötig")
print("=" * 60)