nuropb_gw.handlers.ws_handler

Module Contents

Classes

WsHandler

A Tornado WebSocket handler that does the following:

Data

logger

VALID_SESSION_REQUIRED

API

nuropb_gw.handlers.ws_handler.logger

None

nuropb_gw.handlers.ws_handler.VALID_SESSION_REQUIRED

‘A valid user authorisation is required before a WebSocket connection is established’

class nuropb_gw.handlers.ws_handler.WsHandler(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs: Any)

Bases: tornado.websocket.WebSocketHandler, nuropb_gw.handlers.base_handler.BaseMixin, abc.ABC

A Tornado WebSocket handler that does the following:

  • Authorizing and establishing a WebSocket connection

  • Receiving messages over the connection

  • Sending messages over the connection

  • Registering with the handler manager

  • Unregistering with the handler manager

NOTE: A WebSocket connection can be seamlessly established after a valid web session using the SameSite session cookie. In addition, bearer token authentication is also supported. Where a bearer token present is either present in the Authentication header, or Authorisation cookie, and in that order of preference. this token would override the session cookie.

The bearer token pattern is easily extended to support other authentication methods such as API Keys, OpenID, OAuth2, or SAML.

Initialization

_allowed_origins: Sequence[str]

None

_handler_manager: nuropb_gw.handler_manager.HandlerManager

None

_session_id: str

None

_user_id: str | None

None

_username: str | None

None

_bearer_token: str | None

None

initialize()
property session_id: str

Returns the session id for the WebSocket handler

property user_id: str

Returns the user id for the WebSocket handler

property username: str

Returns the username for the WebSocket handler

property bearer_token: str

Returns a bearer token for the WebSocket handler

update_user_info(user_info) None

Replace BaseMixin.update_user_info() to avoid returning a cookie

Parameters:

user_info

Returns:

check_origin(origin: str) bool
async open()

Called on a WebSocket connection opened event

If the Authorization for the connection can not be established, then it is closed

async on_message(message: str)

Message received over WebSocket as an expected json string, pass it directly to the service manager for further processing

async write_message(message: Any, binary: bool = False) None

Writes a message to the WebSocket, if not binary then serialize the message to json first. It is safe to call this method regardless of the state of the WebSocket connection.

JSON encoding done here, and handling all data type that are not json serializable.

NOTE JSON decoding is handled in the handler manager.

on_close()
safe_close()

Idempotent close method, closes the WebSocket connection regardless of state