Reputation: 125
I'm writing a simple Django app that integrates with a third party API. It fetches some JSON from the third party and displays it in a basic web app. I'm using the OAuth2 Authorization code flow to authenticate with the authentication server.
Any direct communication with the external API happens in functions that are separated from my views - so none of the views call the API directly. They instead will import and call these "service" functions as needed.
As part of the Authorization code flow I need to use the refresh token to get a new access token to continue to fetch resources from the third party. Here is the function that refreshes the access token:
import requests
import environ
### Globals
env = environ.Env()
AUTH_URL = 'https://example.com/oauth/access_token.php'
CLIENT_ID = env('CLIENT_ID')
CLIENT_SECRET = env('CLIENT_SECRET')
...
def refresh_access_token(refresh_token):
"""
uses refresh_token to request another access token
returns the access token
"""
payload = {
'refresh_token': refresh_token,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
}
response = requests.request('POST', AUTH_URL, data=payload)
return response.json()['access_token']
Here's my question - and forgive me if I'm overthinking - but let's say that my refresh token has been revoked by the user. I'll get a 400 Bad Request
status code from the server. So to handle that, I need to change that return line above to be more like this:
if response.status_code == 400:
# throw an exception
else:
return response.json()['access_token']
What would be the cleanest and most pythonic exception to throw? Should I throw Django specific exceptions in "non"-Django code (i.e., not directly in a view)?
Upvotes: 2
Views: 785
Reputation: 125
I ended up just subclassing Exception
with my own, and caught that.
class InvalidGrant(Exception):
pass
...
if response.status_code == 400:
raise InvalidGrant('Your refresh token is invalid.')
return response.json()['access_token']
Upvotes: 2