Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Fix handling of 400 response when refreshing token #38

Merged
merged 2 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions trakt/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ def _refresh_token(s):
'grant_type': 'refresh_token'
}
response = session.post(url, json=data, headers=HEADERS)
s.logger.debug('RESPONSE [post] (%s): %s', url, str(response))
s.logger.debug('RESPONSE [post] (%s): %s - %s', url, str(response), response.content)
if response.status_code == 200:
data = response.json()
OAUTH_TOKEN = data.get("access_token")
Expand All @@ -433,13 +433,14 @@ def _refresh_token(s):
OAUTH_TOKEN=OAUTH_TOKEN, OAUTH_REFRESH=OAUTH_REFRESH,
OAUTH_EXPIRES_AT=OAUTH_EXPIRES_AT
)
elif response.status_code == 401:
s.logger.debug(
"Rejected - Unable to refresh expired OAuth token, "
"refresh_token is invalid"
)
elif response.status_code in (401, 400):
from .errors import OAuthRefreshException
raise OAuthRefreshException(response)
elif response.status_code in s.error_map:
raise s.error_map[response.status_code](response)
else:
from .errors import BadRequestException
raise BadRequestException(response)


def load_config():
Expand Down
15 changes: 15 additions & 0 deletions trakt/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

# Errors for use by PyTrakt
'BadResponseException',
'OAuthRefreshException',

# Exceptions by HTTP status code
# https://trakt.docs.apiary.io/#introduction/status-codes
Expand Down Expand Up @@ -62,6 +63,20 @@ class OAuthException(TraktException):
message = 'Unauthorized - OAuth must be provided'


class OAuthRefreshException(OAuthException):
def __init__(self, response=None):
super().__init__(response)
self.data = self.response.json()

@property
def error(self):
return self.data["error"]

@property
def error_description(self):
return self.data["error_description"]


class ForbiddenException(TraktException):
"""TraktException type to be raised when a 403 return code is received"""
http_code = 403
Expand Down
Loading