Skip to content

Commit

Permalink
Bugfix: Handle authenticating when there is no api_token file (#21)
Browse files Browse the repository at this point in the history
* Handle authenticating when there is no api_token file

* bump version
  • Loading branch information
m4wh6k authored Oct 28, 2022
1 parent 104fe70 commit 657425b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.7.0
0.7.1
19 changes: 15 additions & 4 deletions src/boardwalkd/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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,
)
Expand All @@ -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,
Expand Down

0 comments on commit 657425b

Please sign in to comment.