Spaces:
Paused

File size: 2,472 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4abe06
5eb4857
c4abe06
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
WebSocket endpoints for real-time ticket updates.
"""

from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends, Query
from uuid import UUID
from core.websockets import manager
from core.security import decode_access_token
from core.database import async_session_factory
from sqlalchemy import select
from models.user import User

router = APIRouter()

@router.websocket("/ws/{workspace_id}")
async def ticket_events(
    websocket: WebSocket,
    workspace_id: UUID,
    token: str = Query(...)
):
    """
    WebSocket endpoint for a specific workspace.
    Authenticates via token in query string (since WS headers are limited).
    """
    # 1. Authenticate
    try:
        payload = decode_access_token(token)
        user_id = payload.get("sub")
        token_workspace_id = payload.get("workspace_id")
        role = payload.get("role", "").lower()
        
        # Security Guard: Customers are strictly isolated to their own workspace.
        # Staff (non-customer prefix) are allowed to monitor any workspace they jump into.
        is_customer = role.startswith("customer") or role == "customer"
        
        if is_customer and str(token_workspace_id) != str(workspace_id):
            await websocket.close(code=1008) # Policy Violation
            return
    except Exception:
        await websocket.close(code=1008) # Policy Violation
        return

    await manager.connect(websocket, workspace_id)
    try:
        # Keep alive - wait for messages (though we mainly broadcast)
        while True:
            data = await websocket.receive_text()
            # Handle client-to-server messages if needed
    except WebSocketDisconnect:
        manager.disconnect(websocket, workspace_id)


@router.websocket("/ws/tickets/{ticket_id}")
async def ticket_thread_events(
    websocket: WebSocket,
    ticket_id: UUID,
    token: str = Query(...)
):
    """
    WebSocket endpoint for a specific ticket thread.
    Allows real-time message updates within the thread.
    """
    try:
        payload = decode_access_token(token)
        user_id = payload.get("sub")
        # In a real app, we'd verify the user has access to this ticket
    except Exception:
        await websocket.close(code=1008)
        return

    await manager.connect_ticket(websocket, ticket_id)
    try:
        while True:
            await websocket.receive_text()
    except WebSocketDisconnect:
        manager.disconnect_ticket(websocket, ticket_id)