-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphql_client.py
More file actions
432 lines (338 loc) · 12.5 KB
/
graphql_client.py
File metadata and controls
432 lines (338 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"""Module defining the GraphqlClient class and its help functions."""
import json
import socket
import threading
import webbrowser
from logging import WARNING, basicConfig, getLogger
from pathlib import Path
from queue import Queue
import jwt as pyjwt
import requests
from werkzeug.serving import make_server
from werkzeug.wrappers import Request, Response
__all__ = ["GraphqlClient", "GraphqlError", "get_token"]
basicConfig(level=WARNING)
logger = getLogger(__name__)
class GraphqlError(Exception):
"""Raised if the Graphql query returns any error(s)."""
class DatabaseChoiceError(Exception):
"""Raised when an invalid database choice is provided."""
def __init__(
self, message: str = "Can only handle database prod or test."
) -> None:
"""Initialize the DatabaseChoiceError.
Args:
message (str): Exception message.
Defaults to 'Can only handle database prod or test.'.
"""
super().__init__(message)
class NoInternetError(Exception):
"""Raised when there is no internet connectivity."""
def __init__(self, message: str = "No internet connection.") -> None:
"""Initialize the NoInternetError.
Args:
message (str): Exception message.
Defaults to 'No internet connection.'.
"""
super().__init__(message)
def check_internet(host: str = "8.8.8.8", port: int = 53, timeout: int = 3) -> bool:
"""Check if there is an active internet connection.
Args:
host (str): Host to ping. Defaults to "8.8.8.8".
port (int): Port to use. Defaults to 53.
timeout (int): Timeout in seconds. Defaults to 3.
Returns:
bool: True if internet is available, False otherwise.
"""
try:
socket.setdefaulttimeout(timeout)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((host, port))
except OSError:
return False
else:
return True
def get_dot_config_file_name(filename: str) -> Path:
"""Get the full path to the config file in the user's home directory.
Args:
filename (str): Filename to append to home directory.
Returns:
Path: Path object to the config file.
"""
return Path.home() / filename
def write_token_to_file(jwt_token: str, filename: str) -> None:
"""Write the decoded JWT token to a file.
Args:
jwt_token (str): JWT token string.
filename (str): Target file name to write the token to.
Raises:
FileNotFoundError: If the file could not be written.
"""
dot_config_file_name = get_dot_config_file_name(filename=filename)
data = pyjwt.decode(jwt=jwt_token, options={"verify_signature": False})
database = data["aud"]
if dot_config_file_name.exists():
with dot_config_file_name.open(mode="r", encoding="utf-8") as file_handle:
local_token = json.load(fp=file_handle)
local_token["tokens"][database] = {"token": jwt_token, "decoded": data}
else:
local_token = {"tokens": {database: {"token": jwt_token, "decoded": data}}}
with dot_config_file_name.open(mode="w", encoding="utf-8") as file_handle:
json.dump(obj=local_token, fp=file_handle, indent=2, sort_keys=True)
if not dot_config_file_name.exists():
msg = "Writing token to file failed."
raise FileNotFoundError(msg)
logger_message = f"Wrote token to file: {dot_config_file_name}."
logger.info(logger_message)
def get_token_from_file(database: str, filename: str) -> str:
"""Read the token from a local file.
Args:
database (str): Database identifier.
filename (str): File containing the token.
Returns:
str: Token string.
Raises:
FileNotFoundError: If the token file doesn't exist.
DatabaseChoiceError: If the database is not supported.
"""
dot_config_file_name = get_dot_config_file_name(filename=filename)
if not dot_config_file_name.exists():
msg = f"File '{dot_config_file_name}' with token not found"
raise FileNotFoundError(msg)
with dot_config_file_name.open(mode="r", encoding="utf-8") as file_handle:
dot_config = json.load(fp=file_handle)
try:
token = dot_config["tokens"][database]["token"]
except KeyError as exc:
raise DatabaseChoiceError from exc
logger_message = "get_token_from_file()"
logger.info(logger_message)
return token
def token_get_server(
database: str, base_url: str, filename: str, port: int = 5678
) -> str:
"""Start a temporary server to retrieve a token via browser.
Args:
database (str): Database name.
base_url (str): Base URL for the authentication service.
filename (str): File to store the token.
port (int): Local server port. Defaults to 5678.
Returns:
str: Retrieved token.
Raises:
DatabaseChoiceError: If an unsupported database is given.
NoInternetError: If no internet connection is available.
"""
logger_message = "token_get_server()"
logger.info(logger_message)
if database == "prod":
url_str = ""
elif database == "test":
url_str = "test"
else:
raise DatabaseChoiceError
queue = Queue()
if check_internet():
webbrowser.open(
url=(
f"https://{url_str}portal.{base_url}/token?"
f"redirect_uri=http://localhost:{port}/token"
),
new=2,
)
else:
raise NoInternetError
@Request.application
def app(request: Request) -> Response:
"""Local HTTP handler to receive the API key from the browser."""
queue.put(item=request.args["api_key"])
return Response(
response=""" <!DOCTYPE html>
<html lang=\"en-US\">
<head>
<script>
setTimeout(function () {
window.close();
}, 2000);
</script>
</head>
<body>
<p>Writing token to local machine</p>
</body>
</html> """,
status=200,
content_type="text/html; charset=UTF-8",
)
server = make_server(host="localhost", port=port, app=app)
thread = threading.Thread(target=server.serve_forever)
thread.start()
token = queue.get(block=True)
write_token_to_file(jwt_token=token, filename=filename)
server.shutdown()
thread.join()
return token
def browser_get_token(
database: str,
base_url: str,
filename: str,
timeout: int = 10,
) -> str:
"""Get a valid token from file or trigger browser-based login flow.
Args:
database (str): Database name.
base_url (str): Base URL for the authentication service.
filename (str): Token storage file name.
timeout (int): Timeout for token verification request.
Returns:
str: Validated token.
Raises:
NoInternetError: If internet is not available.
"""
try:
token = get_token_from_file(database=database, filename=filename)
except (FileNotFoundError, DatabaseChoiceError) as exc:
logger_message = f"Getting token from file failed: {exc}"
logger.warning(logger_message)
token = token_get_server(
database=database, base_url=base_url, filename=filename
)
headers = {"accept": "application/json", "Authorization": f"Bearer {token}"}
try:
response = requests.get(
url=f"https://auth.{base_url}/ping",
headers=headers,
timeout=timeout,
)
response.raise_for_status()
except requests.HTTPError as exc:
logger_message = f"Token authorization failed. HTTP error occurred: {exc}"
logger.warning(logger_message)
token = token_get_server(
database=database, base_url=base_url, filename=filename
)
except requests.ConnectionError as exc:
raise NoInternetError from exc
return token
class GraphqlClient:
"""Captor Graphql Client.
Class used to authenticate a user and allow it to fetch data from the
Captor Graphql API.
"""
def __init__(self, database: str = "prod", base_url: str = "captor.se") -> None:
"""Initialize the GraphQLClient.
Args:
database (str): Database name, 'prod' or 'test'. Defaults to 'prod'.
base_url (str): Base domain name. Defaults to 'captor.se'.
Raises:
DatabaseChoiceError: If database is not 'prod' or 'test'.
"""
filename = f".{base_url.split(maxsplit=1, sep='.')[0]}"
self.token = browser_get_token(
database=database,
base_url=base_url,
filename=filename,
)
decoded_token = pyjwt.decode(
jwt=self.token,
options={"verify_signature": False},
)
logger_message = f"token.unique_name: {decoded_token['unique_name']}"
logger.info(logger_message)
self.database = database
if self.database == "prod":
url_str = ""
elif self.database == "test":
url_str = "test"
else:
raise DatabaseChoiceError
self.url = f"https://{url_str}api.{base_url}/graphql"
def query(
self,
query_string: str,
variables: dict | None = None,
timeout: int = 10,
*,
verify: bool = True,
) -> tuple[dict | list | bool | None, dict | list | bool | str | None]:
"""Execute a GraphQL query.
Args:
query_string (str): GraphQL query string.
variables (dict | None): Query variables. Defaults to None.
timeout (int): Request timeout in seconds. Defaults to 10.
verify (bool): Whether to verify SSL cert. Defaults to True.
Returns:
tuple: Tuple of (data, errors) from the query result.
Raises:
NoInternetError: If internet is not available.
"""
headers = {
"Authorization": f"Bearer {self.token}",
"accept-encoding": "gzip",
}
json_data: dict[str, str | dict] = {"query": query_string}
if variables:
json_data["variables"] = variables
try:
response = requests.post(
url=self.url,
json=json_data,
headers=headers,
verify=verify,
timeout=timeout,
)
response.raise_for_status()
except requests.HTTPError as exc:
logger_message = f"Query execution failed. HTTP error occurred: {exc}"
logger.warning(logger_message)
return None, str(exc)
except requests.ConnectionError as exc:
raise NoInternetError from exc
response_data = response.json()
data = response_data.get("data", None)
errors = response_data.get("errors", None)
return data, errors
def get_token(
database: str,
username: str,
password: str,
url: str = "https://auth.captor.se/token",
timeout: int = 10,
) -> str | None:
"""Get a token with a username and password as authentication.
Args:
database (str): Database identifier.
username (str): Username.
password (str): Password.
url (str): Web site address / url.
Defaults to 'https://auth.captor.se/token'
timeout (int): Timeout in seconds. Defaults to 10.
Returns:
str: Token string.
Raises:
DatabaseChoiceError: If the database is not supported.
NoInternetError: If internet is not available.
"""
if database not in ["prod", "test"]:
raise DatabaseChoiceError
try:
response = requests.post(
url=url,
data={
"client_id": database,
"username": username,
"password": password,
"grant_type": "password",
},
timeout=timeout,
)
result: str = response.json().get("access_token", None)
except requests.HTTPError as exc:
logger_message = (
f"POST https://auth.captor.se/token failed. HTTP error occurred: {exc}"
)
logger.warning(logger_message)
return None
except requests.ConnectionError as exc:
raise NoInternetError from exc
else:
return result