From 657425b4cc18be5677fe250d14c7b1891e6fed61 Mon Sep 17 00:00:00 2001 From: Mat Hornbeek <84995001+m4wh6k@users.noreply.github.com> Date: Fri, 28 Oct 2022 15:50:25 -0700 Subject: [PATCH] Bugfix: Handle authenticating when there is no api_token file (#21) * Handle authenticating when there is no api_token file * bump version --- VERSION | 2 +- src/boardwalkd/protocol.py | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/VERSION b/VERSION index faef31a..39e898a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.0 +0.7.1 diff --git a/src/boardwalkd/protocol.py b/src/boardwalkd/protocol.py index 8564daf..12502fd 100644 --- a/src/boardwalkd/protocol.py +++ b/src/boardwalkd/protocol.py @@ -93,10 +93,12 @@ def __init__(self, url: str): self.url = urlparse(url) def get_api_token(self) -> str: + """Retrieves the API token from disk""" return self.api_token_file.read_text().rstrip() async def api_login(self): - """Performs an interactive login to the API and returns a session token""" + """Performs an interactive login to the API and writes the session token + to disk""" match self.url.scheme: case "http": websocket_url = self.url._replace(scheme="ws") @@ -130,12 +132,23 @@ def authenticated_request( """Performs an API request with authentication. By default, auto-prompts for authentication if auth fails""" url = urljoin(self.url.geturl(), path) + + try: + api_token = self.get_api_token() + except FileNotFoundError: + # If there is no token, automatically try to log in + asyncio.run(self.api_login()) + # Always flush the event queue in case any messages were pending on auth + self.flush_event_queue() + + api_token = self.get_api_token() + request = HTTPRequest( method=method, body=body, headers={ "Content-Type": "application/json", - "boardwalk-api-token": self.get_api_token(), + "boardwalk-api-token": api_token, }, url=url, ) @@ -147,10 +160,8 @@ def authenticated_request( if e.code == 403 and auto_login_prompt: # If auth is denied, automatically try to login asyncio.run(self.api_login()) - # Always flush the event queue in case any messages were pending on auth self.flush_event_queue() - # Attempt the request again return self.authenticated_request( path=path,