Skip to content

Commit 9f59c5e

Browse files
committed
more error handling
1 parent 83ab2b6 commit 9f59c5e

File tree

1 file changed

+50
-14
lines changed

1 file changed

+50
-14
lines changed

tokens/__init__.py

+50-14
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,22 @@
1414
TOKENS = {}
1515

1616

17+
class ConfigurationError(Exception):
18+
def __init__(self, msg):
19+
self.msg = msg
20+
21+
def __str__(self):
22+
return 'Configuration error: {}'.format(self.msg)
23+
24+
25+
class InvalidCredentialsError(Exception):
26+
def __init__(self, msg):
27+
self.msg = msg
28+
29+
def __str__(self):
30+
return 'Invalid OAuth credentials: {}'.format(self.msg)
31+
32+
1733
def init_fixed_tokens_from_env():
1834
env_val = os.environ.get('OAUTH2_ACCESS_TOKENS', '')
1935
for part in filter(None, env_val.split(',')):
@@ -36,27 +52,47 @@ def start():
3652
pass
3753

3854

55+
def read_credentials(path):
56+
user_path = os.path.join(path, 'user.json')
57+
try:
58+
with open(user_path) as fd:
59+
user_data = json.load(fd)
60+
except Exception as e:
61+
raise InvalidCredentialsError('Failed to read {}: {}'.format(user_path, e))
62+
63+
client_path = os.path.join(path, 'client.json')
64+
try:
65+
with open(client_path) as fd:
66+
client_data = json.load(fd)
67+
except Exception as e:
68+
raise InvalidCredentialsError('Failed to read {}: {}'.format(client_path, e))
69+
70+
return user_data, client_data
71+
72+
3973
def refresh(token_name):
4074
logger.info('Refreshing access token "%s"..', token_name)
4175
token = TOKENS[token_name]
4276
path = CONFIG['dir']
4377
url = CONFIG['url']
4478

4579
if not url:
46-
raise Exception('Missing OAuth access token URL. ' +
47-
'Either set OAUTH_ACCESS_TOKEN_URL or use tokens.configure(url=..).')
48-
49-
with open(os.path.join(path, 'user.json')) as fd:
50-
user_data = json.load(fd)
51-
with open(os.path.join(path, 'client.json')) as fd:
52-
client_data = json.load(fd)
53-
body = {'grant_type': 'password',
54-
'username': user_data.get('application_username'),
55-
'password': user_data.get('application_password'),
56-
'scope': ' '.join(token['scopes'])}
57-
58-
r = requests.post(url, data=body,
59-
auth=(client_data.get('client_id'), client_data.get('client_secret')))
80+
raise ConfigurationError('Missing OAuth access token URL. ' +
81+
'Either set OAUTH_ACCESS_TOKEN_URL or use tokens.configure(url=..).')
82+
83+
user_data, client_data = read_credentials(path)
84+
85+
try:
86+
body = {'grant_type': 'password',
87+
'username': user_data['application_username'],
88+
'password': user_data['application_password'],
89+
'scope': ' '.join(token['scopes'])}
90+
91+
auth = (client_data['client_id'], client_data['client_secret'])
92+
except KeyError as e:
93+
raise InvalidCredentialsError('Missing key: {}'.format(e))
94+
95+
r = requests.post(url, data=body, auth=auth)
6096
r.raise_for_status()
6197
data = r.json()
6298
token['data'] = data

0 commit comments

Comments
 (0)