Files
Sternsinger/CMBNet/cmbnet/ws/routes.py
T

96 lines
2.8 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
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:
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 token or not broker.authenticate(
tenant_id, account_id, token, session_id
):
ws.close()
break
continue
# Fachliche Nachrichten sind erst nach erfolgreicher
# Authentifizierung erlaubt.
if not broker.is_authenticated(tenant_id, account_id):
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)