2 Commits
Author SHA1 Message Date
admin 8f64760add show build on website footer 2026-07-07 16:12:12 +02:00
admin ffa34815cd Remove legacy admin UI from RollCalc 2026-07-07 12:20:09 +02:00
9 changed files with 144 additions and 634 deletions
+4 -4
View File
@@ -31,11 +31,11 @@ Primary files:
## Planned Direction ## Planned Direction
- The existing admin UI/API in RollCalc is planned for removal. - The previous admin UI/API has been removed from RollCalc.
- Do not expand or repair the admin area unless explicitly requested as a temporary measure. - Do not reintroduce admin screens or admin APIs unless explicitly requested as a temporary measure.
- Keep login/access logging in RollCalc. - Keep login/access logging in RollCalc.
- Administration and maintenance of `article-data.json` should move to a separate application. - Administration and maintenance of `article-data.json` should move to a separate application.
- Treat `templates/admin.html` and `/api/admin/*` expectations as legacy/transitional, not as target architecture. - Treat article-data administration as out of scope for RollCalc.
## Code Style ## Code Style
@@ -73,7 +73,7 @@ These credentials are hardcoded and are a known risk; do not introduce more secr
- Access logging writes to `access_log.json` by reading and rewriting the whole file. - Access logging writes to `access_log.json` by reading and rewriting the whole file.
- The active UI logic is largely inline in `templates/roll_calculator.html`. - The active UI logic is largely inline in `templates/roll_calculator.html`.
- Several `static/*.js` files appear to be older, alternative, or integration modules. Confirm script inclusion before modifying them. - Several `static/*.js` files appear to be older, alternative, or integration modules. Confirm script inclusion before modifying them.
- The admin template and backend admin routes are inconsistent and scheduled for removal rather than expansion. - The previous admin template and backend admin route have been removed; do not rebuild them by default.
- The disclaimer confirmation is client-side only. - The disclaimer confirmation is client-side only.
## Safety Notes ## Safety Notes
+26 -17
View File
@@ -14,13 +14,13 @@ Backend:
- `app.py` creates the Flask app. - `app.py` creates the Flask app.
- HTTP Basic Auth is implemented with `Flask-HTTPAuth`. - HTTP Basic Auth is implemented with `Flask-HTTPAuth`.
- Users are currently hardcoded in `BETA_USERS` and `ADMIN_USERS`. - Users are currently hardcoded in `BETA_USERS`.
- `/` renders the active calculator template. - `/` renders the active calculator template.
- `/static/<path:filename>` is intended to serve static files behind Basic Auth. - `/static/<path:filename>` is intended to serve static files behind Basic Auth.
- `/api/health` returns health/version information. - `/api/health` returns health/version information.
- `/api/user` returns the authenticated user and admin flag. - `/api/user` returns the authenticated user.
- `/admin/logs` returns access logs for admin users.
- Access events are appended to `access_log.json`. - Access events are appended to `access_log.json`.
- `build_info.json` is loaded at startup and exposed to all templates as `build_info`.
Frontend: Frontend:
@@ -29,6 +29,26 @@ Frontend:
- `window.ARTICLE_DATA` is loaded from `/static/article-data.json`. - `window.ARTICLE_DATA` is loaded from `/static/article-data.json`.
- `window.APP_CONFIG` is currently defined inline for forklift rules. - `window.APP_CONFIG` is currently defined inline for forklift rules.
- A disclaimer modal blocks use until the user checks the confirmation checkbox. - A disclaimer modal blocks use until the user checks the confirmation checkbox.
- The footer displays build metadata: version, branch, commit, and timestamp.
## Build Info
Build/deployment metadata is read from:
```text
build_info.json
```
Expected fields:
- `version`
- `branch`
- `commit`
- `timestamp`
If `build_info.json` is missing, malformed, or does not contain a usable value, RollCalc falls back to `unknown` for that value and continues serving the site.
The data is loaded centrally in `app.py` and made available to every template as `build_info`.
## Roll Geometry ## Roll Geometry
@@ -184,25 +204,14 @@ This is client-side only. It is not persisted, logged, or enforced server-side.
## Admin Area State ## Admin Area State
Current backend route: RollCalc no longer contains an admin UI or admin API. The previous `/admin/logs` route and `templates/admin.html` have been removed.
```text Login/access logging remains part of RollCalc, but log viewing and article-data administration should not be implemented inside this app. Maintenance of `article-data.json` is planned for a separate application.
/admin/logs
```
Current `templates/admin.html` expects:
```text
/api/admin/stats
/api/admin/logs
```
Those `/api/admin/*` endpoints are not currently implemented in `app.py`, and there is no route rendering `templates/admin.html`.
## Known Technical Risks ## Known Technical Risks
- Hardcoded plaintext credentials in `app.py`. - Hardcoded plaintext credentials in `app.py`.
- Basic Auth only; no sessions or role framework beyond user dictionaries. - Basic Auth only; no sessions or role framework beyond the user dictionary.
- `access_log.json` is rewritten on every logged request and is not concurrency-safe. - `access_log.json` is rewritten on every logged request and is not concurrency-safe.
- No log rotation or retention policy is implemented. - No log rotation or retention policy is implemented.
- Flask's default static route may conflict with the intended authenticated `/static/<path:filename>` behavior; verify effective routing before relying on protected static files. - Flask's default static route may conflict with the intended authenticated `/static/<path:filename>` behavior; verify effective routing before relying on protected static files.
+22 -20
View File
@@ -42,7 +42,7 @@ If port `5000` is already occupied, start through Flask's CLI without changing f
flask --app app run --host 127.0.0.1 --port 5001 flask --app app run --host 127.0.0.1 --port 5001
``` ```
The app uses HTTP Basic Auth. Current credentials are defined in `BETA_USERS` and `ADMIN_USERS` in `app.py`. The app uses HTTP Basic Auth. Current credentials are defined in `BETA_USERS` in `app.py`.
## Project Layout ## Project Layout
@@ -51,14 +51,14 @@ The app uses HTTP Basic Auth. Current credentials are defined in `BETA_USERS` an
├── app.py ├── app.py
├── requirements.txt ├── requirements.txt
├── README.md ├── README.md
├── build_info.json
├── access_log.json ├── access_log.json
├── config.json ├── config.json
├── article-data_.json ├── article-data_.json
├── fix_article_data.py ├── fix_article_data.py
├── service-worker.js ├── service-worker.js
├── templates/ ├── templates/
│ ├── roll_calculator.html │ └── roll_calculator.html
│ └── admin.html
├── static/ ├── static/
│ ├── article-data.json │ ├── article-data.json
│ ├── config.json │ ├── config.json
@@ -88,10 +88,9 @@ Implemented routes:
| `/` | `GET` | Basic Auth | Renders `templates/roll_calculator.html`. | | `/` | `GET` | Basic Auth | Renders `templates/roll_calculator.html`. |
| `/static/<path:filename>` | `GET` | Basic Auth | Intended protected static-file serving from `static/`. | | `/static/<path:filename>` | `GET` | Basic Auth | Intended protected static-file serving from `static/`. |
| `/api/health` | `GET` | Basic Auth | Returns app health and version. | | `/api/health` | `GET` | Basic Auth | Returns app health and version. |
| `/api/user` | `GET` | Basic Auth | Returns current authenticated user and admin flag. | | `/api/user` | `GET` | Basic Auth | Returns current authenticated user info. |
| `/admin/logs` | `GET` | Basic Auth plus admin check | Returns `access_log.json` contents. |
Authentication is implemented with `Flask-HTTPAuth`. The current code merges `BETA_USERS` and `ADMIN_USERS` and performs direct plaintext string comparison. Authentication is implemented with `Flask-HTTPAuth`. The current code checks `BETA_USERS` and performs direct plaintext string comparison.
Access logging is handled by `log_access()`, which reads `access_log.json`, appends a record, and writes the whole file back. Access logging is handled by `log_access()`, which reads `access_log.json`, appends a record, and writes the whole file back.
@@ -103,6 +102,7 @@ The template contains:
- Page layout and all main CSS. - Page layout and all main CSS.
- A disclaimer modal shown after Basic Auth login and before calculator use. - A disclaimer modal shown after Basic Auth login and before calculator use.
- Footer build metadata from `build_info`.
- Global state: - Global state:
- `window.ARTICLE_DATA` - `window.ARTICLE_DATA`
- `window.APP_CONFIG` - `window.APP_CONFIG`
@@ -243,20 +243,9 @@ These provide or describe range calculations for material thickness, area weight
### Admin UI ### Admin UI
There are admin-oriented HTML files: RollCalc no longer contains an admin UI or admin API. Login/access logging remains in the backend, but logs are not exposed through a RollCalc admin screen.
- `templates/admin.html` Administration and maintenance of `article-data.json` is planned for a separate application. RollCalc should continue to consume `static/article-data.json` read-only.
- `admin.html`
- `admin_simple.html`
The backend currently exposes `/admin/logs`, but `templates/admin.html` expects:
```text
/api/admin/stats
/api/admin/logs
```
Those `/api/admin/*` routes are not implemented in `app.py` at the time this README was written. There is also no route currently rendering `templates/admin.html`.
## Static Assets and Data Files ## Static Assets and Data Files
@@ -274,6 +263,19 @@ JSON audit log written by `app.py`.
Important implementation detail: each logged access reads and rewrites the entire JSON file. This is simple but not concurrency-safe and can become inefficient as the file grows. Important implementation detail: each logged access reads and rewrites the entire JSON file. This is simple but not concurrency-safe and can become inefficient as the file grows.
### `build_info.json`
Deployment/build metadata displayed in the site footer.
Expected fields:
- `version`
- `branch`
- `commit`
- `timestamp`
`app.py` loads this file centrally at startup and exposes it to all templates as `build_info`. If the file is missing, invalid, or a field is empty, the affected values fall back to `unknown` and the website continues to work.
### `fix_article_data.py` ### `fix_article_data.py`
Utility script that updates relative frontend fetch/register paths to Flask-style `/static/...` paths and checks that key static files exist. Utility script that updates relative frontend fetch/register paths to Flask-style `/static/...` paths and checks that key static files exist.
@@ -293,7 +295,7 @@ Utility script that updates relative frontend fetch/register paths to Flask-styl
- `access_log.json` is not safe for concurrent writes. - `access_log.json` is not safe for concurrent writes.
- `access_log.json` grows without rotation or retention limits. - `access_log.json` grows without rotation or retention limits.
- The custom `/static/<path:filename>` route is intended to protect static files, but Flask also creates a default static route unless disabled. Verify effective route behavior before relying on static-file protection. - The custom `/static/<path:filename>` route is intended to protect static files, but Flask also creates a default static route unless disabled. Verify effective route behavior before relying on static-file protection.
- Admin frontend and backend routes are currently inconsistent. - RollCalc no longer includes an admin UI/API; article data administration belongs in a separate application.
- There is no visible automated test suite. - There is no visible automated test suite.
- The main template is large and mixes layout, styling, data loading, calculations, and UI behavior. - The main template is large and mixes layout, styling, data loading, calculations, and UI behavior.
- The disclaimer confirmation is client-side only and is not persisted or audited server-side. - The disclaimer confirmation is client-side only and is not persisted or audited server-side.
+28
View File
@@ -600,5 +600,33 @@
"endpoint": "/", "endpoint": "/",
"method": "GET", "method": "GET",
"status": 200 "status": 200
},
{
"timestamp": "2026-07-07T11:44:53.524315",
"username": "mtazl",
"endpoint": "/",
"method": "GET",
"status": 200
},
{
"timestamp": "2026-07-07T11:47:36.702455",
"username": "mtazl",
"endpoint": "/",
"method": "GET",
"status": 200
},
{
"timestamp": "2026-07-07T12:18:47.866971",
"username": "mtazl",
"endpoint": "/",
"method": "GET",
"status": 200
},
{
"timestamp": "2026-07-07T14:46:22.335316",
"username": "mtazl",
"endpoint": "/",
"method": "GET",
"status": 200
} }
] ]
+38 -25
View File
@@ -27,13 +27,45 @@ BETA_USERS = {
"controlling": "beta2026" # ⚠️ ÄNDERN! "controlling": "beta2026" # ⚠️ ÄNDERN!
} }
# Optional: Admin-Features (z.B. Logs, Stats)
ADMIN_USERS = {
"admin": "admin_secure_pwd_2026" # ⚠️ ÄNDERN!
}
# Logging für Auditing # Logging für Auditing
LOG_FILE = "access_log.json" LOG_FILE = "access_log.json"
BUILD_INFO_FILE = "build_info.json"
UNKNOWN_BUILD_INFO = {
"version": "unknown",
"branch": "unknown",
"commit": "unknown",
"timestamp": "unknown"
}
# ============================================================================
# BUILD INFO
# ============================================================================
def load_build_info():
"""Load deployment/build metadata for templates."""
try:
with open(BUILD_INFO_FILE, "r") as f:
data = json.load(f)
except Exception as e:
print(f"[Build Info Error] {e}")
return UNKNOWN_BUILD_INFO.copy()
if not isinstance(data, dict):
return UNKNOWN_BUILD_INFO.copy()
build_info = UNKNOWN_BUILD_INFO.copy()
for key in build_info:
value = data.get(key)
if isinstance(value, str) and value.strip():
build_info[key] = value.strip()
return build_info
BUILD_INFO = load_build_info()
@app.context_processor
def inject_build_info():
"""Make build metadata available in all templates."""
return {"build_info": BUILD_INFO}
# ============================================================================ # ============================================================================
# AUTHENTICATION # AUTHENTICATION
@@ -42,8 +74,7 @@ LOG_FILE = "access_log.json"
@auth.verify_password @auth.verify_password
def verify_password(username, password): def verify_password(username, password):
"""Verify HTTP Basic Auth credentials""" """Verify HTTP Basic Auth credentials"""
all_users = {**BETA_USERS, **ADMIN_USERS} if username in BETA_USERS and BETA_USERS[username] == password:
if username in all_users and all_users[username] == password:
return username return username
return None return None
@@ -96,30 +127,12 @@ def health_check():
def get_user(): def get_user():
"""Get current authenticated user info""" """Get current authenticated user info"""
user = auth.current_user() user = auth.current_user()
is_admin = user in ADMIN_USERS
return jsonify({ return jsonify({
"username": user, "username": user,
"authenticated": True, "authenticated": True,
"is_admin": is_admin,
"timestamp": datetime.now().isoformat() "timestamp": datetime.now().isoformat()
}), 200 }), 200
@app.route("/admin/logs", methods=["GET"])
@auth.login_required
def get_logs():
"""View access logs - admin only"""
user = auth.current_user()
if user not in ADMIN_USERS:
log_access(user, "/admin/logs", "GET", 403)
return jsonify({"error": "Unauthorized"}), 403
log_access(user, "/admin/logs", "GET")
logs = []
if os.path.exists(LOG_FILE):
with open(LOG_FILE, "r") as f:
logs = json.load(f)
return jsonify({"logs": logs}), 200
# ============================================================================ # ============================================================================
# ERROR HANDLERS # ERROR HANDLERS
# ============================================================================ # ============================================================================
+6
View File
@@ -0,0 +1,6 @@
{
"version": "0.4",
"branch": "develop/v0.4",
"commit": "ffa3481",
"timestamp": "2026-07-07T10:26:13Z"
}
+16
View File
@@ -0,0 +1,16 @@
#!/bin/bash
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
cat > build_info.json <<EOF
{
"version": "v0.4-dev",
"branch": "$(git branch --show-current)",
"commit": "$(git rev-parse --short HEAD)",
"timestamp": "$(date -Iseconds)"
}
EOF
-568
View File
@@ -1,568 +0,0 @@
<!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>
+4
View File
@@ -60,6 +60,7 @@
.fc-req-nok { color: #dc3545; font-weight: 600; } .fc-req-nok { color: #dc3545; font-weight: 600; }
.formula-box { background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 6px; padding: 10px 14px; font-size: 12px; color: #666; margin-top: 18px; font-family: 'Courier New', monospace; } .formula-box { background: #f8f9fa; border: 1px solid #e0e0e0; border-radius: 6px; padding: 10px 14px; font-size: 12px; color: #666; margin-top: 18px; font-family: 'Courier New', monospace; }
.footer { text-align: center; font-size: 11px; color: #aaa; padding: 18px; margin-top: 30px; } .footer { text-align: center; font-size: 11px; color: #aaa; padding: 18px; margin-top: 30px; }
.footer-build-info { margin-top: 6px; color: #bbb; }
.disclaimer-overlay { .disclaimer-overlay {
position: fixed; position: fixed;
inset: 0; inset: 0;
@@ -844,6 +845,9 @@
<div class="footer"> <div class="footer">
Naue GmbH & Co. KG · Roll Diameter Calculator · Internal Application Naue GmbH & Co. KG · Roll Diameter Calculator · Internal Application
<div class="footer-build-info">
Version {{ build_info.version }} · Branch {{ build_info.branch }} · Commit {{ build_info.commit }} · Built {{ build_info.timestamp }}
</div>
</div> </div>
<script> <script>