164 lines
5.6 KiB
Python
164 lines
5.6 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 Client-ID. Die Client-ID wird pro Webview erzeugt.
|
|
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, Client-ID) aus dem Code-0-Payload.
|
|
|
|
Ältere Clients senden statt ``client_id`` noch ``session_id``. Der
|
|
alte Schlüssel wird übergangsweise weiter akzeptiert.
|
|
"""
|
|
if isinstance(value, dict):
|
|
return (
|
|
value.get('token'),
|
|
value.get('client_id') or 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('client_id') or 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
|
|
|
|
# Die Verbindung wird erst mit dem Code-0-Handshake registriert. Vorher
|
|
# ist die Client-ID noch nicht bekannt.
|
|
client_id = None
|
|
|
|
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
|
|
if client_id:
|
|
msg._sender_client_id = client_id
|
|
|
|
# Code 0: Authentifizierung über den Einmal-Token und Registrierung
|
|
# der Client-ID.
|
|
if msg.code == 0:
|
|
if client_id:
|
|
broker.log_incoming(
|
|
tenant_id, msg, recipients=[client_id],
|
|
note='Code-0-Handshake nach bereits erfolgreicher Authentifizierung'
|
|
)
|
|
ws.close()
|
|
break
|
|
|
|
token, requested_client_id = _parse_auth_payload(msg.msg)
|
|
if not requested_client_id:
|
|
requested_client_id = getattr(msg, 'client_id', None)
|
|
client_id = broker.normalize_client_id(requested_client_id, account_id)
|
|
msg.client_id = client_id
|
|
|
|
if not token or not broker.register_connection(
|
|
tenant_id, account_id, client_id, ws
|
|
):
|
|
broker.log_incoming(
|
|
tenant_id, msg, recipients=[],
|
|
note='Code-0-Registrierung fehlgeschlagen'
|
|
)
|
|
current_app.logger.warning(
|
|
'WebSocket-Registrierung fehlgeschlagen: tenant=%s account=%s client=%s',
|
|
tenant_id, account_id, client_id
|
|
)
|
|
ws.close()
|
|
break
|
|
|
|
if not broker.authenticate(tenant_id, account_id, client_id, token):
|
|
broker.log_incoming(
|
|
tenant_id, msg, recipients=[client_id],
|
|
note='Code-0-Handshake fehlgeschlagen'
|
|
)
|
|
current_app.logger.warning(
|
|
'WebSocket-Authentifizierung fehlgeschlagen: tenant=%s account=%s client=%s',
|
|
tenant_id, account_id, client_id
|
|
)
|
|
ws.close()
|
|
break
|
|
|
|
broker.log_incoming(
|
|
tenant_id, msg, recipients=[client_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,
|
|
client_id,
|
|
WSMessage(sender_id=0, code=0, msg='authenticated').to_json()
|
|
)
|
|
continue
|
|
|
|
# Fachliche Nachrichten sind erst nach erfolgreicher
|
|
# Authentifizierung erlaubt.
|
|
if not client_id or not broker.is_authenticated(tenant_id, client_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, client_id=client_id
|
|
)
|
|
|
|
except Exception as exc:
|
|
print(f'WebSocket error: {exc}')
|
|
finally:
|
|
if client_id:
|
|
broker.remove_connection(tenant_id, client_id, ws)
|