nxtlo / aiobungie

Python and asyncio Bungie API wrapper.
https://nxtlo.github.io/aiobungie/
MIT License
52 stars 10 forks source link

Error occurs when OAuth token is invalid/expired #143

Closed GregShiner closed 2 years ago

GregShiner commented 2 years ago

Long story short.

If the token given to any function that uses OAuth is invalid or expired, bungie.net returns an HTML error that rest.py fails to parse.

Expected Result

The simplest solution would be to catch this specific error (401 unauthorized) and raise a more specific and helpful error than the one shown below.

Actual Result

Traceback (most recent call last):
  File "/home/gman1230321/bountyoptimizer/Bounty-Optimization-Tool/app.py", line 83, in getQuests
    raise e
  File "/home/gman1230321/bountyoptimizer/Bounty-Optimization-Tool/app.py", line 75, in getQuests
    player = await client.fetch_current_user_memberships(request.headers["Authorization"])
  File "/home/gman1230321/bountyoptimizer/Bounty-Optimization-Tool/lib/python3.9/site-packages/aiobungie/client.py", line 177, in fetch_current_user_memberships
    resp = await self.rest.fetch_current_user_memberships(access_token)
  File "/home/gman1230321/bountyoptimizer/Bounty-Optimization-Tool/lib/python3.9/site-packages/aiobungie/rest.py", line 457, in _request
    data: typedefs.JSONObject = await response.json()
  File "/home/gman1230321/bountyoptimizer/Bounty-Optimization-Tool/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 1103, in json
    raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url=URL('https://www.bungie.net/Platform/User/GetMembershipsForCurrentUser/')

The error shown here makes it really unclear what actually happened. All a normal user could maybe deduce is that Bungie is returning HTML as opposed to JSON. But I know that the specific time this error occurred, it was caused by Bungie returning 401 unauthorized. response.status when this error is thrown is 401.

System info

OS: Ubuntu 20.04.03 LTS Python: 3.9.5 aiobungie: 0.2.5

Further info

nxtlo commented 2 years ago

Thanks for reporting that, This is supposed to be handled as intended here and here, but i can see where the issue is happening, the await response.json() line is being called before checking if the response status is == 200, so when you get 401 Bungie returns an HTML instead of JSON. which gets kinda funky with my impl for reading JSON only. anyways I will fix this ASAP.

nxtlo commented 2 years ago

Also the response code its returning is actually 500 internal error not 401, which's why i'm hardcoding this to return useful information.