Deployment vorbereitet mit URI-Prefix

This commit is contained in:
concierge committed 2026-10-29 16:22:46 +01:00
1 parent b41c3bc3a6
commit fa02a7ade0
11 files changed
+183 -22

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
# CMBNet hinter Caddy unter einem URI-Prefix (Beispiel: /cmbnet)
#
# Die Anwendung erwartet den öffentlichen Prefix im Header
# "X-Forwarded-Prefix". Flask setzt daraus SCRIPT_NAME; alle mit url_for
# erzeugten URLs und die clientseitigen AJAX-/WebSocket-URLs enthalten den
# Prefix dann automatisch.
#
# Wichtig: Der Flask-Port darf nicht direkt aus dem Internet erreichbar sein,
# damit Clients den Header nicht selbst setzen können.
example.com {
# /cmbnet -> /cmbnet/ (damit relative URLs korrekt aufgelöst werden)
redir /cmbnet /cmbnet/ 308
# ------------------------------------------------------------------
# Variante A (empfohlen): handle_path entfernt /cmbnet, bevor die
# Anfrage an Flask geht. Der Header teilt Flask den Prefix mit.
# ------------------------------------------------------------------
handle_path /cmbnet/* {
reverse_proxy 127.0.0.1:5000 {
header_up X-Forwarded-Prefix /cmbnet
}
}
# Optional: Alle anderen Pfade auf die Anwendung umleiten.
handle {
redir /cmbnet/ 308
}
}
# ----------------------------------------------------------------------
# Variante B: Der Prefix bleibt im Pfad erhalten.
#
# Die Middleware erkennt, dass PATH_INFO mit dem Prefix beginnt, und
# schneidet ihn einmalig ab. Ansonsten identisch zu Variante A.
#
# example.com {
# redir /cmbnet /cmbnet/ 308
#
# handle /cmbnet/* {
# reverse_proxy 127.0.0.1:5000 {
# header_up X-Forwarded-Prefix /cmbnet
# }
# }
# }
#
# WebSocket-Verbindungen (/<prefix>/<tenant>/ws) werden von Caddys
# reverse_proxy automatisch unterstützt; es ist keine zusätzliche
# Konfiguration nötig.
+28
View File
@@ -18,6 +18,34 @@ flask --app cmbnet run --debug --host 127.0.0.1 --port 5000
Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV). Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV).
## Betrieb hinter einem Reverse-Proxy (URI-Prefix)
Die Anwendung kann unter einem beliebigen Pfad ausgeliefert werden, z. B.
`https://example.com/cmbnet/`. Dazu muss der Proxy den öffentlichen Prefix im
Header `X-Forwarded-Prefix` setzen:
```caddyfile
example.com {
redir /cmbnet /cmbnet/ 308
handle_path /cmbnet/* {
reverse_proxy 127.0.0.1:5000 {
header_up X-Forwarded-Prefix /cmbnet
}
}
}
```
Die Middleware in `cmbnet/__init__.py` setzt daraus `SCRIPT_NAME`, sodass
`url_for` alle Links, Formularziele und statischen Dateien mit Prefix erzeugt.
Der Prefix wird außerdem als `CMBNET_BASE_URL` an JavaScript übergeben; AJAX-
und WebSocket-Aufrufe bilden ihre URLs damit korrekt. Eine vollständige
Beispielkonfiguration (auch für Proxys, die den Prefix nicht entfernen) steht
in `Caddyfile.example`.
Wichtig: Der Flask-Port sollte nur für den Reverse-Proxy erreichbar sein, damit
Clients den Header nicht selbst setzen können.
## Erste Einrichtung ## Erste Einrichtung
Nach der Initialisierung der Datenbank müssen noch Mandanten und ein Admin-Account angelegt werden. Nach der Initialisierung der Datenbank müssen noch Mandanten und ein Admin-Account angelegt werden.
+73 -7
View File
@@ -3,20 +3,86 @@ from flask import Flask, g, session, send_from_directory
from config import config from config import config
from cmbnet.extensions import sock from cmbnet.extensions import sock
def normalize_prefix(value):
"""Normalisiert einen URI-Prefix aus ``X-Forwarded-Prefix``.
Akzeptiert nur absolute Pfade ohne Query/Fragment, ohne ``..``-Segmente
und ohne doppelte bzw. abschließende Schrägstriche. Bei ungültigen oder
gefährlichen Werten wird ein leerer Prefix zurückgegeben.
"""
if not value:
return ''
# Mehrfach-Header bzw. kommaseparierte Werte: erster Wert zählt.
value = value.split(',', 1)[0].strip()
if not value.startswith('/'):
return ''
if '://' in value or '?' in value or '#' in value or '\\' in value:
return ''
segments = []
for segment in value.split('/'):
if not segment:
continue
if segment in ('.', '..'):
return ''
if any(ord(char) < 32 or ord(char) == 127 for char in segment):
return ''
if '%2f' in segment.lower() or '%5c' in segment.lower():
return ''
segments.append(segment)
return '/' + '/'.join(segments) if segments else ''
class PrefixMiddleware: class PrefixMiddleware:
"""Macht Reverse-Proxy-Prefixe über ``SCRIPT_NAME`` verfügbar.
Der Proxy kann den Prefix vor dem Weiterleiten entfernen (z. B. mit
Caddys ``handle_path``) oder unverändert durchreichen. Beide Varianten
werden unterstützt. Flask erzeugt danach alle ``url_for``-URLs inklusive
Prefix; zusätzlich wird der Prefix an die Templates weitergegeben, damit
JavaScript seine AJAX- und WebSocket-URLs korrekt bilden kann.
"""
def __init__(self, app, prefix=''): def __init__(self, app, prefix=''):
self.app = app self.app = app
self.prefix = prefix self.prefix = normalize_prefix(prefix)
def __call__(self, environ, start_response): def __call__(self, environ, start_response):
script_name = environ.get('HTTP_X_FORWARDED_PREFIX', '') header_prefix = normalize_prefix(environ.get('HTTP_X_FORWARDED_PREFIX'))
if script_name: prefix = header_prefix or self.prefix
environ['SCRIPT_NAME'] = script_name if not prefix:
path_info = environ.get('PATH_INFO', '') return self.app(environ, start_response)
if path_info.startswith(script_name):
environ['PATH_INFO'] = path_info[len(script_name):] script_name = environ.get('SCRIPT_NAME', '') or ''
if script_name == '/':
script_name = ''
script_name = script_name.rstrip('/')
# Nicht doppelt prefixen, wenn die Anwendung bereits unter demselben
# Pfad eingebunden ist (z. B. durch den WSGI-Server).
if script_name and (
script_name == prefix or script_name.endswith(prefix)
):
combined_script_name = script_name
else:
combined_script_name = script_name + prefix
path_info = environ.get('PATH_INFO', '') or '/'
# Proxy hat den Prefix nicht entfernt: einmalig abschneiden.
if path_info == prefix:
path_info = '/'
elif path_info.startswith(prefix + '/'):
path_info = path_info[len(prefix):]
environ['SCRIPT_NAME'] = combined_script_name
environ['PATH_INFO'] = path_info or '/'
return self.app(environ, start_response) return self.app(environ, start_response)
def create_app(config_name=None): def create_app(config_name=None):
if config_name is None: if config_name is None:
config_name = os.environ.get('FLASK_ENV', 'development') config_name = os.environ.get('FLASK_ENV', 'development')
+3 -2
View File
@@ -1,5 +1,6 @@
const tenant = window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const apiBase = `/${tenant}/admin/api`; const tenant = window.CMBNET_TENANT || '';
const apiBase = appUrl(`${tenant}/admin/api`);
function changeRole(accountId, role) { function changeRole(accountId, role) {
fetch(`${apiBase}/accounts/${accountId}/role`, { fetch(`${apiBase}/accounts/${accountId}/role`, {
+4 -2
View File
@@ -1,8 +1,10 @@
const tenantCode = window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const tenantCode = window.CMBNET_TENANT || '';
const apiBase = appUrl(`${tenantCode}/admin/api`);
async function loadBrokerStatus() { async function loadBrokerStatus() {
try { try {
const response = await fetch(`/${tenantCode}/admin/api/broker/status`); const response = await fetch(`${apiBase}/broker/status`);
if (!response.ok) { if (!response.ok) {
throw new Error('Failed to load status'); throw new Error('Failed to load status');
} }
+3 -2
View File
@@ -1,5 +1,6 @@
const tenant = window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const apiBase = `/${tenant}/admin/api`; const tenant = window.CMBNET_TENANT || '';
const apiBase = appUrl(`${tenant}/admin/api`);
const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig']; const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig'];
let currentGroupId = null; let currentGroupId = null;
+3 -2
View File
@@ -1,5 +1,6 @@
const tenant = window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const apiBase = `/${tenant}/admin/api`; const tenant = window.CMBNET_TENANT || '';
const apiBase = appUrl(`${tenant}/admin/api`);
let currentStreetId = null; let currentStreetId = null;
let editMode = false; let editMode = false;
+4 -3
View File
@@ -7,9 +7,10 @@
* 3. Karte, Polylines, Marker und Kontrollansicht aufbauen * 3. Karte, Polylines, Marker und Kontrollansicht aufbauen
*/ */
const tenant = window.CMBNET_TENANT || window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const apiBase = `/${tenant}/api`; const tenant = window.CMBNET_TENANT || '';
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/${tenant}/ws`; const apiBase = appUrl(`${tenant}/api`);
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}${appUrl(`${tenant}/ws`)}`;
const storageKey = `cmbnet:${tenant}:map`; const storageKey = `cmbnet:${tenant}:map`;
const themeStorageKey = 'cmbnet:theme'; const themeStorageKey = 'cmbnet:theme';
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null; const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
+5 -4
View File
@@ -1,9 +1,10 @@
/* /*
* Mobile Views: Dispatcher-Mobil & Gruppen * Mobile Views: Dispatcher-Mobil & Gruppen
*/ */
const tenant = window.CMBNET_TENANT || window.location.pathname.split('/')[1]; const appUrl = window.CMBNET_APP_URL || ((path) => `/${String(path || '').replace(/^\/+/, '')}`);
const apiBase = `/${tenant}/api`; const tenant = window.CMBNET_TENANT || '';
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}/${tenant}/ws`; const apiBase = appUrl(`${tenant}/api`);
const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://${window.location.host}${appUrl(`${tenant}/ws`)}`;
const storageKey = `cmbnet:${tenant}:mobile`; const storageKey = `cmbnet:${tenant}:mobile`;
const viewMode = window.CMBNET_VIEW_MODE || 'mobile_dispatcher'; const viewMode = window.CMBNET_VIEW_MODE || 'mobile_dispatcher';
const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null; const currentAccountId = Number(window.CMBNET_ACCOUNT_ID) || null;
@@ -315,7 +316,7 @@ function bindTabs() {
function bindButtons() { function bindButtons() {
const logout = document.getElementById('mobileLogout'); const logout = document.getElementById('mobileLogout');
if (logout) logout.addEventListener('click', () => {window.location.href = window.CMBNET_LOGOUT_URL || '/';}); if (logout) logout.addEventListener('click', () => {window.location.href = window.CMBNET_LOGOUT_URL || appUrl('');});
const todoBtn = document.getElementById('mobileTodoBtn'); const todoBtn = document.getElementById('mobileTodoBtn');
if (todoBtn) todoBtn.addEventListener('click', openStreetSelectDialog); if (todoBtn) todoBtn.addEventListener('click', openStreetSelectDialog);
+11
View File
@@ -17,6 +17,17 @@
} }
})(); })();
</script> </script>
<script>
// Basis-Pfad für alle clientseitigen URLs. Bei einem Reverse-Proxy
// mit X-Forwarded-Prefix enthält SCRIPT_NAME z. B. "/cmbnet".
window.CMBNET_BASE_URL = {{ request.script_root|tojson }};
window.CMBNET_TENANT = {{ (session.get('tenant_code') or '')|tojson }};
window.CMBNET_APP_URL = function (path) {
const base = (window.CMBNET_BASE_URL || '').replace(/\/+$/, '');
const clean = String(path == null ? '' : path).replace(/^\/+/, '');
return clean ? base + '/' + clean : (base || '/');
};
</script>
<link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/pico.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/leaflet.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">