mirror of
https://github.com/joaovitoriasilva/endurain.git
synced 2026-01-08 23:38:01 -05:00
Replaces websocket.schema with websocket.manager for managing WebSocket connections, introducing a singleton WebSocketManager and updating all imports and usages accordingly. Adds token-based authentication for WebSocket connections, requiring access_token as a query parameter and validating it server-side. Updates FastAPI WebSocket endpoint to use authenticated user ID, and modifies frontend to connect using the access token. Removes obsolete schema.py and improves error handling and logging for WebSocket events.
39 lines
1.1 KiB
Python
39 lines
1.1 KiB
Python
from fastapi import HTTPException, status
|
|
|
|
import websocket.manager as websocket_manager
|
|
|
|
|
|
async def notify_frontend(
|
|
user_id: int,
|
|
websocket_manager: websocket_manager.WebSocketManager,
|
|
json_data: dict,
|
|
) -> bool:
|
|
"""
|
|
Send a JSON message to a user's WebSocket connection.
|
|
|
|
Attempts to send data to the user's WebSocket. For MFA
|
|
verification, raises an exception if no connection exists.
|
|
|
|
Args:
|
|
user_id: The target user's identifier.
|
|
websocket_manager: The WebSocket connection manager.
|
|
json_data: JSON-serializable data to send.
|
|
|
|
Returns:
|
|
True if message was sent, False if no connection.
|
|
|
|
Raises:
|
|
HTTPException: If MFA_REQUIRED but no connection exists.
|
|
"""
|
|
websocket = websocket_manager.get_connection(user_id)
|
|
if websocket:
|
|
await websocket.send_json(json_data)
|
|
return True
|
|
|
|
if json_data.get("message") == "MFA_REQUIRED":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"No WebSocket connection for user {user_id}",
|
|
)
|
|
return False
|