Files
Sternsinger/CMBNet/cmbnet/ws/routes.py
T
2026-10-31 19:14:52 +01:00

127 lines
4.2 KiB
Python

"""
WebSocket Routes
Ablauf einer Verbindung:
1. Client verbindet sich mit /<tenant>/ws.
2. Client sendet Code 0 mit dem zuvor über die API geholten Einmal-Token
und seiner persistenten Sitzungs-ID.
3. Erst nach erfolgreicher Prüfung dürfen fachliche Nachrichten gesendet
werden. Vorher wird die Verbindung geschlossen.
"""
import json
from flask import session, current_app
from cmbnet.extensions import sock
from cmbnet.ws import broker
from cmbnet.ws.protocol import WSMessage
def _parse_auth_payload(value):
"""Liefert (Token, Sitzungs-ID) aus dem Code-0-Payload."""
if isinstance(value, dict):
return value.get('token'), value.get('session_id')
if isinstance(value, str):
text = value.strip()
if text.startswith('{'):
try:
data = json.loads(text)
except (TypeError, ValueError):
return None, None
if isinstance(data, dict):
return data.get('token'), data.get('session_id')
return text, None
return None, None
@sock.route('/<tenant>/ws')
def ws(ws, tenant):
"""WebSocket Endpoint"""
from cmbnet.db import get_db
db = get_db()
tenant_row = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant,)).fetchone()
if not tenant_row:
ws.close()
return
tenant_id = tenant_row['id']
account_id = session.get('account_id')
if not account_id:
ws.close()
return
# Verbindung registrieren, aber noch nicht als authentifiziert markieren.
if not broker.register_connection(tenant_id, account_id, ws):
ws.close()
return
try:
while True:
data = ws.receive()
if data is None:
break
msg = WSMessage.from_json(data)
if not msg:
current_app.logger.warning(
'WebSocket-Nachricht ist kein gültiges JSON: tenant=%s account=%s length=%s',
tenant_id, account_id, len(data)
)
continue
# Die Absender-ID stammt immer aus der Session und kann vom Client
# nicht gefälscht werden.
msg.sender_id = account_id
# Code 0: Authentifizierung über den Einmal-Token.
if msg.code == 0:
token, session_id = _parse_auth_payload(msg.msg)
if not session_id:
session_id = getattr(msg, 'session_id', None)
if session_id:
msg.session_id = session_id
if not token or not broker.authenticate(
tenant_id, account_id, token, session_id
):
broker.log_incoming(
tenant_id, msg, recipients=[],
note='Code-0-Handshake fehlgeschlagen'
)
current_app.logger.warning(
'WebSocket-Authentifizierung fehlgeschlagen: tenant=%s account=%s',
tenant_id, account_id
)
ws.close()
break
broker.log_incoming(
tenant_id, msg, recipients=[account_id],
note='Code-0-Handshake erfolgreich'
)
# Bestätigt dem Client den erfolgreichen Handshake. Erst jetzt
# darf er gepufferte fachliche Nachrichten senden.
broker.send_to_connection(
tenant_id,
account_id,
WSMessage(sender_id=0, code=0, msg='authenticated').to_json()
)
continue
# Fachliche Nachrichten sind erst nach erfolgreicher
# Authentifizierung erlaubt.
if not broker.is_authenticated(tenant_id, account_id):
broker.log_incoming(
tenant_id, msg, recipients=[],
note='Nachricht vor Code-0-Authentifizierung'
)
ws.close()
break
broker.route_message(tenant_id, msg, apply_business=True)
except Exception as exc:
print(f'WebSocket error: {exc}')
finally:
broker.remove_connection(tenant_id, account_id, ws)