Skip to content

Commit 0751b3b

Browse files
Token writeback toggle and logging (#60)
* add writeback toggle * increase logging
1 parent 3995488 commit 0751b3b

6 files changed

Lines changed: 474 additions & 328 deletions

File tree

setup.py

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,31 +3,23 @@
33
from setuptools import setup, find_packages
44

55
setup(
6-
name='sumo-wrapper-python',
7-
description='Python wrapper for the Sumo API',
8-
url='https://github.com/equinor/sumo-wrapper-python',
9-
keywords='sumo, python',
6+
name="sumo-wrapper-python",
7+
description="Python wrapper for the Sumo API",
8+
url="https://github.com/equinor/sumo-wrapper-python",
9+
keywords="sumo, python",
1010
classifiers=[
11-
'Development Status :: 3 - Alpha',
12-
'Intended Audience :: Developers',
13-
'Natural Language :: English',
14-
'Programming Language :: Python :: 3.7'
15-
'Programming Language :: Python :: 3.8'
16-
],
17-
version='0.1.4',
18-
author='Equinor ASA',
19-
install_requires=[
20-
'requests',
21-
'msal',
22-
'PyYAML',
23-
'setuptools'
24-
],
11+
"Development Status :: 3 - Alpha",
12+
"Intended Audience :: Developers",
13+
"Natural Language :: English",
14+
"Programming Language :: Python :: 3.7" "Programming Language :: Python :: 3.8",
15+
],
16+
version="0.1.4",
17+
author="Equinor ASA",
18+
install_requires=["requests", "msal", "PyYAML", "setuptools"],
2519
python_requires=">=3.4",
2620
packages=find_packages("src"),
2721
package_dir={"": "src"},
2822
include_package_data=True,
2923
zip_safe=False,
30-
entry_points={
31-
"console_scripts": ["sumo_login = sumo.wrapper.login:main"]
32-
}
24+
entry_points={"console_scripts": ["sumo_login = sumo.wrapper.login:main"]},
3325
)

src/sumo/wrapper/_auth.py

Lines changed: 73 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,16 @@
44
import stat
55
import sys
66
import os
7+
import logging
8+
9+
logging.basicConfig(
10+
format="%(asctime)s %(levelname)-8s %(message)s",
11+
level=logging.INFO,
12+
datefmt="%Y-%m-%d %H:%M:%S",
13+
)
14+
15+
logger = logging.getLogger(__name__)
16+
logger.setLevel(level="DEBUG")
717

818
TENANT = "3aa4a235-b6e2-48d5-9195-7fcf05b459b0"
919

@@ -14,13 +24,24 @@
1424

1525
class Auth:
1626
def __init__(
17-
self, client_id, resource_id, authority=AUTHORITY_URI, client_credentials=None
27+
self,
28+
client_id,
29+
resource_id,
30+
authority=AUTHORITY_URI,
31+
client_credentials=None,
32+
writeback=False,
1833
):
34+
35+
logger.debug("Initialize Auth")
1936
self.client_id = client_id
37+
logger.debug("client_id is %s", self.client_id)
2038
self.resource_id = resource_id
39+
logger.debug("client_id is %s", self.client_id)
2140
self.scope = self.resource_id + "/.default"
2241
self.authority = authority
2342
self.client_credentials = client_credentials
43+
self.writeback = writeback
44+
logger.debug("self.writeback is %s", self.writeback)
2445
self.token_path = os.path.join(
2546
HOME_DIR, ".sumo", str(self.resource_id) + ".token"
2647
)
@@ -31,33 +52,57 @@ def __init__(
3152
client_credential=self.client_credentials,
3253
token_cache=self.cache,
3354
)
55+
56+
logger.debug("self.app has been initialized")
57+
logger.debug("Getting accounts")
3458
self.accounts = self.app.get_accounts()
3559

60+
logger.debug("self.accounts is %s", self.accounts)
61+
3662
if self._cache_available():
3763
if not self.accounts:
38-
print("Token cache found but have no accounts")
39-
self._oauth_device_code()
64+
logger.debug("Token cache found but have no accounts")
65+
raise RuntimeError(
66+
"The locally stored token has no accounts. "
67+
"Please check your access or run 'sumo_login' to re-create your token."
68+
)
4069
else:
70+
logger.debug("There are accounts. Calling _oauth_get_token_silent()")
4171
self._oauth_get_token_silent()
4272
else:
43-
print("No token cache found, reauthenticate")
73+
logger.debug("No token cache found, reauthenticate")
4474
self._oauth_device_code()
4575

4676
def get_token(self):
47-
if self.is_token_expired():
77+
logger.debug("Starting get_token")
78+
79+
is_expired = self.is_token_expired()
80+
81+
logger.debug("self.is_token_expired is %s", str(is_expired))
82+
83+
if is_expired:
4884
self._oauth_get_token_silent()
4985

86+
logger.debug(
87+
"Returning access_token. Length of access token is %s",
88+
len(self.result["access_token"]),
89+
)
5090
return self.result["access_token"]
5191

5292
def is_token_expired(self):
5393
"""
5494
Check if token is expired or about to expire.
5595
"""
56-
return datetime.datetime.now() > self.expiring_date
96+
logger.debug("is_token_expired() is starting")
97+
is_expired = datetime.datetime.now() > self.expiring_date
98+
logger.debug("is_expired: %s", str(is_expired))
99+
return is_expired
57100

58101
def _oauth_get_token_silent(self):
102+
logger.debug("_oauth_get_token_silent starting")
103+
logger.info("Getting access token")
59104
if not self.accounts:
60-
print("Get accounts")
105+
logger.debug("Get accounts")
61106
self.accounts = self.app.get_accounts()
62107

63108
if not self._check_token_security():
@@ -68,14 +113,19 @@ def _oauth_get_token_silent(self):
68113
)
69114

70115
if "access_token" in self.result:
71-
print("Token found")
116+
logger.info("Access token found")
72117
elif "error" in self.result:
73-
print("Error getting access token" + self.result["error"])
118+
logger.info("Error getting access token")
119+
logger.debug(self.result["error"])
74120
else:
75-
print("Acuire token failed")
121+
logger.info("Failed getting access token")
76122

77123
self._set_expiring_date(int(self.result["expires_in"]))
78-
self._write_cache()
124+
125+
if self.writeback:
126+
self._write_cache()
127+
128+
logger.debug("_oauth_get_token_silent() has finished")
79129

80130
def _set_expiring_date(self, time_left, threshold=60):
81131
"""
@@ -88,10 +138,13 @@ def _set_expiring_date(self, time_left, threshold=60):
88138
self.expiring_date = datetime.datetime.now() + datetime.timedelta(
89139
seconds=time_left - threshold
90140
)
141+
logger.debug("self.expiring_date set to %s", self.expiring_date)
91142

92143
def _cache_available(self):
93144
if os.path.isfile(self.token_path):
145+
logger.debug("cache is available")
94146
return True
147+
logger.debug("cache is not available")
95148
return False
96149

97150
def _check_token_security(self):
@@ -110,22 +163,24 @@ def _oauth_device_code(self):
110163
"Fail to create device flow. Err: %s" % json.dumps(flow, indent=4)
111164
)
112165
else:
113-
print(flow["message"])
166+
logger.debug("flow[message] is %s", flow["message"])
114167

115168
self.result = self.app.acquire_token_by_device_flow(flow)
116169
try:
117170
self._set_expiring_date(int(self.result["expires_in"]))
118171
except KeyError:
119-
print(self.result)
172+
logger.debug(self.result)
120173
self._write_cache()
121174

122175
def _write_cache(self):
176+
logger.debug("Writing cache")
123177
old_mask = os.umask(0o077)
124178

125179
dir_path = os.path.dirname(self.token_path)
126180
os.makedirs(dir_path, exist_ok=True)
127181

128182
with open(self.token_path, "w") as file:
183+
logger.debug("Writing to %s", self.token_path)
129184
file.write(self.cache.serialize())
130185

131186
if not sys.platform.lower().startswith("win"):
@@ -136,17 +191,21 @@ def _write_cache(self):
136191

137192
def _read_cache(self):
138193
with open(self.token_path, "r") as file:
194+
logger.debug("Reading from %s", self.token_path)
139195
self.cache.deserialize(file.read())
140196

141197
def _get_cache(self):
142198

199+
logger.debug("_get_cache")
143200
self.cache = msal.SerializableTokenCache()
201+
144202
if self._cache_available():
203+
logger.debug("cache is available, reading it")
145204
self._read_cache()
146205

147206

148207
if __name__ == "__main__":
149208
auth = Auth(
150209
"1826bd7c-582f-4838-880d-5b4da5c3eea2", "88d2b022-3539-4dda-9e66-853801334a86"
151210
)
152-
print(auth.get_token())
211+
logger.debug(auth.get_token())

0 commit comments

Comments
 (0)