main.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import socketio
  2. from apps.webui.models.users import Users
  3. from utils.utils import decode_token
  4. sio = socketio.AsyncServer(cors_allowed_origins=[], async_mode="asgi")
  5. app = socketio.ASGIApp(sio, socketio_path="/ws/socket.io")
  6. # Dictionary to maintain the user pool
  7. USER_POOL = {}
  8. @sio.event
  9. async def connect(sid, environ, auth):
  10. print("connect ", sid)
  11. user = None
  12. data = decode_token(auth["token"])
  13. if data is not None and "id" in data:
  14. user = Users.get_user_by_id(data["id"])
  15. if user:
  16. USER_POOL[sid] = {
  17. "id": user.id,
  18. "name": user.name,
  19. "email": user.email,
  20. "role": user.role,
  21. }
  22. print(f"user {user.name}({user.id}) connected with session ID {sid}")
  23. else:
  24. print("Authentication failed. Disconnecting.")
  25. await sio.disconnect(sid)
  26. @sio.event
  27. def disconnect(sid):
  28. if sid in USER_POOL:
  29. disconnected_user = USER_POOL.pop(sid)
  30. print(f"user {disconnected_user} disconnected with session ID {sid}")
  31. else:
  32. print(f"Unknown session ID {sid} disconnected")
  33. @sio.event
  34. def disconnect(sid):
  35. print("disconnect", sid)