Skip to content

Commit 3995488

Browse files
Catch proxyerror and be verbose when encounter KeyError (#59)
* catch proxyerror and be verbose when encounter KeyError
1 parent 037d7d7 commit 3995488

3 files changed

Lines changed: 147 additions & 115 deletions

File tree

setup.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,8 @@
1414
'Programming Language :: Python :: 3.7'
1515
'Programming Language :: Python :: 3.8'
1616
],
17-
version='0.1.3',
17+
version='0.1.4',
1818
author='Equinor ASA',
19-
author_email='llag@equinor.com',
2019
install_requires=[
2120
'requests',
2221
'msal',

src/sumo/wrapper/_auth.py

Lines changed: 42 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,30 @@
77

88
TENANT = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0"
99

10-
AUTHORITY_HOST_URI = 'https://login.microsoftonline.com'
11-
AUTHORITY_URI = AUTHORITY_HOST_URI + '/' + TENANT
12-
HOME_DIR = os.path.expanduser('~')
10+
AUTHORITY_HOST_URI = "https://login.microsoftonline.com"
11+
AUTHORITY_URI = AUTHORITY_HOST_URI + "/" + TENANT
12+
HOME_DIR = os.path.expanduser("~")
1313

1414

1515
class Auth:
16-
17-
def __init__(self, client_id, resource_id, authority=AUTHORITY_URI, client_credentials=None):
16+
def __init__(
17+
self, client_id, resource_id, authority=AUTHORITY_URI, client_credentials=None
18+
):
1819
self.client_id = client_id
1920
self.resource_id = resource_id
2021
self.scope = self.resource_id + "/.default"
2122
self.authority = authority
2223
self.client_credentials = client_credentials
23-
self.token_path = os.path.join(HOME_DIR, ".sumo", str(self.resource_id) + ".token")
24+
self.token_path = os.path.join(
25+
HOME_DIR, ".sumo", str(self.resource_id) + ".token"
26+
)
2427
self._get_cache()
25-
self.app = msal.PublicClientApplication(self.client_id, authority=AUTHORITY_URI,
26-
client_credential=self.client_credentials, token_cache=self.cache)
28+
self.app = msal.PublicClientApplication(
29+
self.client_id,
30+
authority=AUTHORITY_URI,
31+
client_credential=self.client_credentials,
32+
token_cache=self.cache,
33+
)
2734
self.accounts = self.app.get_accounts()
2835

2936
if self._cache_available():
@@ -36,7 +43,6 @@ def __init__(self, client_id, resource_id, authority=AUTHORITY_URI, client_crede
3643
print("No token cache found, reauthenticate")
3744
self._oauth_device_code()
3845

39-
4046
def get_token(self):
4147
if self.is_token_expired():
4248
self._oauth_get_token_silent()
@@ -45,7 +51,7 @@ def get_token(self):
4551

4652
def is_token_expired(self):
4753
"""
48-
Check if token is expired or about to expire.
54+
Check if token is expired or about to expire.
4955
"""
5056
return datetime.datetime.now() > self.expiring_date
5157

@@ -55,37 +61,41 @@ def _oauth_get_token_silent(self):
5561
self.accounts = self.app.get_accounts()
5662

5763
if not self._check_token_security():
58-
raise SystemError('The token is not stored safely.')
64+
raise SystemError("The token is not stored safely.")
5965

60-
self.result = self.app.acquire_token_silent_with_error([self.scope], account=self.accounts[0])
66+
self.result = self.app.acquire_token_silent_with_error(
67+
[self.scope], account=self.accounts[0]
68+
)
6169

6270
if "access_token" in self.result:
6371
print("Token found")
6472
elif "error" in self.result:
6573
print("Error getting access token" + self.result["error"])
6674
else:
6775
print("Acuire token failed")
68-
69-
self._set_expiring_date(int(self.result['expires_in']))
76+
77+
self._set_expiring_date(int(self.result["expires_in"]))
7078
self._write_cache()
7179

7280
def _set_expiring_date(self, time_left, threshold=60):
7381
"""
74-
Defines the access token expiring date. Sets a threshold to update the token before it expires
82+
Defines the access token expiring date. Sets a threshold to update the token before it expires
7583
76-
Parameter
77-
time_left: time, in seconds, until the token expires.
78-
threshold: how many seconds before expiration the token is allowed to be updated.
84+
Parameter
85+
time_left: time, in seconds, until the token expires.
86+
threshold: how many seconds before expiration the token is allowed to be updated.
7987
"""
80-
self.expiring_date = datetime.datetime.now() + datetime.timedelta(seconds=time_left - threshold)
88+
self.expiring_date = datetime.datetime.now() + datetime.timedelta(
89+
seconds=time_left - threshold
90+
)
8191

8292
def _cache_available(self):
8393
if os.path.isfile(self.token_path):
8494
return True
8595
return False
8696

8797
def _check_token_security(self):
88-
if sys.platform.lower().startswith('win'):
98+
if sys.platform.lower().startswith("win"):
8999
return True
90100

91101
access_stats = os.stat(self.token_path)
@@ -97,12 +107,16 @@ def _oauth_device_code(self):
97107

98108
if "user_code" not in flow:
99109
raise ValueError(
100-
"Fail to create device flow. Err: %s" % json.dumps(flow, indent=4))
110+
"Fail to create device flow. Err: %s" % json.dumps(flow, indent=4)
111+
)
101112
else:
102-
print(flow['message'])
113+
print(flow["message"])
103114

104115
self.result = self.app.acquire_token_by_device_flow(flow)
105-
self._set_expiring_date(int(self.result['expires_in']))
116+
try:
117+
self._set_expiring_date(int(self.result["expires_in"]))
118+
except KeyError:
119+
print(self.result)
106120
self._write_cache()
107121

108122
def _write_cache(self):
@@ -114,7 +128,7 @@ def _write_cache(self):
114128
with open(self.token_path, "w") as file:
115129
file.write(self.cache.serialize())
116130

117-
if not sys.platform.lower().startswith('win'):
131+
if not sys.platform.lower().startswith("win"):
118132
os.chmod(self.token_path, 0o600)
119133
os.chmod(dir_path, 0o700)
120134

@@ -131,6 +145,8 @@ def _get_cache(self):
131145
self._read_cache()
132146

133147

134-
if __name__ == '__main__':
135-
auth = Auth("1826bd7c-582f-4838-880d-5b4da5c3eea2", "88d2b022-3539-4dda-9e66-853801334a86")
148+
if __name__ == "__main__":
149+
auth = Auth(
150+
"1826bd7c-582f-4838-880d-5b4da5c3eea2", "88d2b022-3539-4dda-9e66-853801334a86"
151+
)
136152
print(auth.get_token())

0 commit comments

Comments
 (0)