def on_post(self, req, resp): """Authenticate the user and returns an access token. Expected request: { "username": "******", "password": "******""" client = ElmoClient(settings.base_url, settings.vendor) username = req.media.get("username") password = req.media.get("password") if username is None or password is None: raise falcon.HTTPBadRequest(description="Missing username and password") try: token = client.auth(username, password) except PermissionDenied: raise falcon.HTTPForbidden(description="Wrong username or password") except APIException as e: log.error("503 ServiceUnavailable: {}".format(e)) raise falcon.HTTPServiceUnavailable(description="".format(e)) resp.media = {"access_token": token} resp.status = falcon.HTTP_200
def _acquire_system_lock(self, token, code): """Shared code to avoid duplication between endpoints. It handles `ElmoClient` initialization, gaining the lock and handling errors returned from Elmo API. This function is created as a context manager so actions executed in the caller have the global system lock. """ # Initialize the client with a bearer token client = ElmoClient(settings.base_url, settings.vendor) client._session_id = token try: with client.lock(code): yield client except PermissionDenied: raise falcon.HTTPUnauthorized( description="The bearer token is invalid or expired" ) except APIException as e: # This status may lead to a case where the system is locked. # The global system lock is automatically released after one # minute. Unfortunately it's not possible to recover this state # other than providing credentials in every call (making useless # the bearer token). log.error("503 ServiceUnavailable: {}".format(e)) raise falcon.HTTPServiceUnavailable(description="".format(e))
def __init__(self, host, vendor, username, password, states_config): """Initialize the elmo client wrapper.""" self._username = username self._password = password self._states_config = states_config self._data = None self.state = None self.states = None self.zones = None self.inputs = None ElmoClient.__init__(self, host, vendor)
def test_client_constructor(): """Should build the client using the base URL and the vendor suffix.""" client = ElmoClient("https://example.com", "vendor") assert client._router._base_url == "https://example.com" assert client._router._vendor == "vendor" assert client._session_id is None
def test_client_constructor_with_session_id(): """Should build the client with a provided `session_id`.""" client = ElmoClient("https://example.com", "vendor", session_id="test") assert client._session_id == "test"
def client(): """Create an ElmoClient with unlimited expiration time.""" client = ElmoClient("https://example.com", "domain") yield client
def client(): """Create an ElmoClient with a default base URL.""" client = ElmoClient("https://example.com", "vendor") yield client