python-eigen-ingenuity-nocli 0.5.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. eigeningenuity/__init__.py +29 -0
  2. eigeningenuity/assetmodel.py +433 -0
  3. eigeningenuity/auth.py +178 -0
  4. eigeningenuity/core/__init__.py +236 -0
  5. eigeningenuity/elastic.py +171 -0
  6. eigeningenuity/events.py +88 -0
  7. eigeningenuity/historian.py +786 -0
  8. eigeningenuity/historianmulti.py +481 -0
  9. eigeningenuity/settings.py +87 -0
  10. eigeningenuity/smartdash.py +103 -0
  11. eigeningenuity/sql.py +132 -0
  12. eigeningenuity/util.py +548 -0
  13. modelbuilder/__init__.py +7 -0
  14. modelbuilder/src/__init__.py +0 -0
  15. modelbuilder/src/assetmodelbuilder.py +164 -0
  16. modelbuilder/src/assetmodelcsvwriter.py +31 -0
  17. modelbuilder/src/assetmodelutilities.py +51 -0
  18. modelbuilder/src/configmanager.py +500 -0
  19. modelbuilder/src/connectors/__init__.py +0 -0
  20. modelbuilder/src/connectors/boltconnector.py +108 -0
  21. modelbuilder/src/connectors/dbconnectors.py +40 -0
  22. modelbuilder/src/connectors/genericconnector.py +30 -0
  23. modelbuilder/src/connectors/httpsconnector.py +132 -0
  24. modelbuilder/src/csvcontentsmanager.py +135 -0
  25. modelbuilder/src/csvwriter.py +305 -0
  26. modelbuilder/src/fileanalyser.py +91 -0
  27. modelbuilder/src/filemanager.py +400 -0
  28. modelbuilder/src/messages.py +61 -0
  29. modelbuilder/src/processors/__init__.py +0 -0
  30. modelbuilder/src/processors/cypherfileprocessor.py +73 -0
  31. modelbuilder/src/processors/labelmanager.py +133 -0
  32. modelbuilder/src/processors/nodefileprocessor.py +282 -0
  33. modelbuilder/src/processors/propertymanager.py +129 -0
  34. modelbuilder/src/processors/relationshipfileprocessor.py +285 -0
  35. modelbuilder/src/processors/relationshipmanager.py +31 -0
  36. modelbuilder/src/queries/__init__.py +0 -0
  37. modelbuilder/src/queries/cypherbuilder.py +323 -0
  38. modelbuilder/src/queries/query.py +82 -0
  39. modelbuilder/src/queries/typedefs.py +180 -0
  40. modelbuilder/src/versionmanager.py +356 -0
  41. python_eigen_ingenuity_nocli-0.5.6.dist-info/METADATA +30 -0
  42. python_eigen_ingenuity_nocli-0.5.6.dist-info/RECORD +44 -0
  43. python_eigen_ingenuity_nocli-0.5.6.dist-info/WHEEL +5 -0
  44. python_eigen_ingenuity_nocli-0.5.6.dist-info/top_level.txt +2 -0
@@ -0,0 +1,29 @@
1
+ """Eigen Ingenuity
2
+
3
+ Interface to the Eigen Ingenuity system.
4
+
5
+ Set the EIGENSERVER environment variable either to hostname, hostname:port
6
+ or http://hostname:port/prefix/path as appropriate. It defaults to
7
+ localhost:8080.
8
+
9
+ The various get_XXX methods instantiate connections to different parts
10
+ of the Eigen Ingenuity infrastructure.
11
+
12
+ h = get_historian("instancename")
13
+ h.listDataTags()
14
+ """
15
+
16
+ from __future__ import (absolute_import, division, print_function, unicode_literals)
17
+ import pkg_resources
18
+ from eigeningenuity.core import EigenServer
19
+ from eigeningenuity.historian import get_historian, list_historians, get_default_historian_name
20
+ from eigeningenuity.historianmulti import get_historian_multi
21
+ from eigeningenuity.elastic import get_elastic
22
+ from eigeningenuity.events import get_eventlog
23
+ from eigeningenuity.assetmodel import get_assetmodel
24
+ from eigeningenuity.smartdash import get_smartdash
25
+ from eigeningenuity.sql import get_sql
26
+ from eigeningenuity.settings import set_azure_client_id, set_azure_tenant_id, disable_azure_auth, disable_auth_token_cache, clear_auth_token_cache, set_api_token
27
+
28
+ __all__ = ["get_historian", "get_historian_multi", "get_assetmodel", "get_elastic", "get_sql", "get_eventlog", "get_smartdash", "list_historians", "EigenServer", "set_azure_client_id", "set_azure_tenant_id", "disable_azure_auth", "disable_auth_token_cache", "clear_auth_token_cache", "set_api_token"]
29
+ __version__ = pkg_resources.require("python-eigen-ingenuity")[0].version
@@ -0,0 +1,433 @@
1
+ """Eigen Ingenuity - Asset Model
2
+
3
+ This package deals with the Eigen Ingenuity Asset Model API, by means
4
+ of the Cypher plugin endpoint.
5
+
6
+ To retrieve an AssetObject use getMatchingNodes, or execute a custom cypher query with executeRawQuery
7
+
8
+ from eigeningenuity.assetmodel import getAssetModel
9
+ from eigeningenuity import EigenServer
10
+
11
+ eigenserver = EigenServer(ingenuity-base-url)
12
+
13
+ model = getAssetModel(eigenserver)
14
+
15
+ nodes = model.getMatchingNodes("code","System_")
16
+
17
+
18
+ """
19
+ import functools
20
+
21
+ import requests, os
22
+ import json
23
+ import pandas as pd
24
+ from eigeningenuity import EigenServer
25
+ from urllib.parse import quote as urlquote
26
+ from eigeningenuity.util import force_list, _do_eigen_json_request, parse_properties, get_eigenserver, constructURL, cypherRespMap
27
+ from eigeningenuity.core import get_default_server
28
+ from requests.exceptions import ConnectionError
29
+ from urllib.error import URLError
30
+ from typing import Union
31
+ import datetime as dt
32
+ from datetime import datetime
33
+
34
+ from urllib3.exceptions import InsecureRequestWarning
35
+ requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
36
+
37
+ class AssetModel (object):
38
+ """An assetmodel instance which talks the Eigen Neo4j endpoint.
39
+ """
40
+ def __init__(self, baseurl, auth):
41
+ """This is a constructor. It takes in a URL like https://demo.eigen.co/ei-applet/"""
42
+ self.baseurl = baseurl
43
+ self.eigenserver = get_eigenserver(baseurl)
44
+ self.auth = auth
45
+
46
+ def _testConnection(self):
47
+ """Preflight Request to verify connection to ingenuity"""
48
+ try:
49
+ status = requests.get(self.baseurl, verify=False).status_code
50
+ except (URLError, ConnectionError):
51
+ raise ConnectionError("Failed to connect to ingenuity instance at " + self.baseurl + ". Please check the url is correct and the instance is up.")
52
+
53
+ def _doJsonCypherRequest(self, cmd, params):
54
+ # self._testConnection()
55
+ url = self.baseurl + "jcypher?cmd=" + urlquote(cmd)
56
+ return _do_eigen_json_request(url, self.auth, **params)
57
+
58
+ def _doJsonCommonMenuRequest(self, index, params):
59
+ # self._testConnection()
60
+ url = self.baseurl + "commonmenu2/asset/" + index + "?"
61
+ return _do_eigen_json_request(url, self.auth, **params)
62
+
63
+ def executeRawQuery(self,query:str,output:str="json"):
64
+ """
65
+ Executes a raw cypher query against AssetModel via the AssetModel API.
66
+
67
+ Args:
68
+ query: A string containing a query in cypher, for information on cypher queries see https://neo4j.com/developer/cypher/
69
+
70
+ Returns:
71
+ A Json containing the cypher response to the query.
72
+
73
+ Raises:
74
+ KeyError: Raises an exception
75
+
76
+ """
77
+ args = {'q': query}
78
+ response = self._doJsonCypherRequest("execute", args)
79
+
80
+ if output == "raw":
81
+ return response
82
+ if output == "json":
83
+ if type(response) == list and len(response) == 1:
84
+ return response[0]
85
+ else:
86
+ return response
87
+ if output == "df":
88
+ return pd.json_normalize(response)
89
+
90
+
91
+
92
+ def getRelatedAssetsCommonMenu(self, node: str, output="json", filepath = None):
93
+ """
94
+ Return all measurement tags directly related to a given asset via the Common Menu API.
95
+
96
+ Args:
97
+ node:
98
+ output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
99
+
100
+ Returns:
101
+ A Json containing all nodes with a relation to any node that meets the criteria, and their relationship type.
102
+
103
+ Raises:
104
+ KeyError: Raises an exception
105
+
106
+ """
107
+ args = {"asset": node}
108
+
109
+ response = self._doJsonCommonMenuRequest("relatedAssets", args)
110
+ relatedassets = response["relatedAssets"]["graphapi"]
111
+
112
+ newAssets=[]
113
+
114
+ for item in relatedassets:
115
+ relations = item["relations"]
116
+ for relation in relations:
117
+ newItem = {"asset": item["asset"]}
118
+ newItem["relationName"] = relation["relationName"]
119
+ newItem["direction"] = relation["direction"]
120
+ newAssets.append(newItem)
121
+
122
+
123
+
124
+ if output == "raw":
125
+ return response
126
+ if output == "json":
127
+ return newAssets
128
+ if output == "df":
129
+ return pd.json_normalize(newAssets).drop(columns=["asset.externalId"])
130
+ if output == "file":
131
+ if filepath is None:
132
+ filepath = node + "-RelatedAssets-" + str(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
133
+ with open(filepath + ".json", "w") as f:
134
+ f.write(json.dumps(newAssets, indent=4))
135
+
136
+ def getRelatedMeasurementsCypher(self, query:str, prop:str="code", measurement:str="", output="json"):
137
+ """
138
+ Return all measurement tags directly related to a given asset via the AssetModel API.
139
+
140
+ Args:
141
+ nodes: The value of the property to match
142
+ prop (Optional): The property on to query nodes on. Defaults to code.
143
+ measurement (Optional): Return only tags for a specified measurement type. Defaults to return all tags.
144
+
145
+ Returns:
146
+ A Json containing all nodes with a relation to any node that meets the criteria, and their relationship type.
147
+
148
+ Raises:
149
+ KeyError: Raises an exception
150
+
151
+ """
152
+ result = []
153
+ exact = True
154
+ for item in force_list(query):
155
+ x = []
156
+ y = []
157
+ args = {}
158
+ # if exact:
159
+ matchStatement = "n.%s = '%s' and r.measurementName contains '%s'" % (prop, item, measurement)
160
+ # else:
161
+ # matchStatement = "n.%s contains '%s' and r.measurementName contains '%s'" % (prop, node, measurement)
162
+ args['q'] = 'MATCH (n)-[r:hashistoriantag]->(m) WHERE %s RETURN r.measurementName as measurementName, m.code as measurementCode' % matchStatement
163
+
164
+ response = self._doJsonCypherRequest("execute", args)
165
+
166
+
167
+ for meas in response:
168
+ x.append(meas["measurementName"])
169
+ y.append(meas["measurementCode"])
170
+
171
+ result.append(pd.Series(y,index=x,name=item))
172
+ k = pd.merge(result[0],result[1],on="index")
173
+ if output == "raw":
174
+ return response
175
+ if output == "json":
176
+ return response
177
+ if output == "df":
178
+ return pd.DataFrame(response)
179
+
180
+ def getRelatedMeasurementsCommonMenu(self, node:str, output="json"):
181
+ """
182
+ Return all measurement tags directly related to a given asset via the Common Menu API.
183
+
184
+ Args:
185
+ node: The code (ID) of the node to get related measurements from
186
+ output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API, "json" - A processed version of the json response, "df" - A formatted pandas dataframe object. Defaults to "json".
187
+
188
+ Returns:
189
+ A Json containing all nodes with a relation to any node that meets the criteria, and their relationship type.
190
+
191
+ Raises:
192
+ KeyError: Raises an exception
193
+
194
+ """
195
+ args = {}
196
+ args["asset"] = node
197
+
198
+ response = self._doJsonCommonMenuRequest("timeseries", args)
199
+ timeseries = response["timeseries"]
200
+
201
+ if output == "raw":
202
+ return response
203
+ if output == "json":
204
+ return timeseries
205
+ if output == "df":
206
+ return pd.DataFrame(timeseries)["tag"]
207
+
208
+ def getRelatedDocuments(self, node:Union[str,list], match=None, output="json", directory:str=None):
209
+ """
210
+ Return all Documents related to nodes via the Common Menu API.
211
+
212
+ Args:
213
+ node: The name of the node to query documents for
214
+ match (Optional): Filter returned Documents to those with filenames matching a string
215
+ output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API; "json" - A processed version of the json response; "df" - A formatted pandas dataframe object; "download" - Downloads the files to a local directory"
216
+ directory (Optional): Name and path to the directory created/used for downloaded documents. If omitted, will download files to current directory. Has no effect unless output is "download".
217
+
218
+ Returns:
219
+ The set of all documents related to the nodes, the format is dependent on the output parameter. If output is "download", it returns instead the files themselves
220
+
221
+ Raises:
222
+ KeyError: Raises an exception
223
+
224
+ """
225
+ nodes = force_list(node)
226
+ results = []
227
+ documents = []
228
+ for node in nodes:
229
+ args = {}
230
+ args["asset"] = node
231
+ response = self._doJsonCommonMenuRequest("documents", args)
232
+ results.append(response)
233
+ documents.append(response["documents"])
234
+
235
+ if documents == [[]]:
236
+ return []
237
+ documents = documents[0][0]["documents"]
238
+
239
+ documents = list(map(functools.partial(constructURL, self.eigenserver), documents))
240
+
241
+ matches = []
242
+ if match is not None:
243
+ for document in documents:
244
+ if match in document['fileName'] or match in document['description']:
245
+ matches.append(document)
246
+ documents = matches
247
+
248
+ if output == "raw":
249
+ return results
250
+ if output == "json":
251
+ return documents
252
+ if output == "df":
253
+ return pd.json_normalize(documents)
254
+ if output == "download":
255
+ if directory is None:
256
+ directory = "."
257
+ os.makedirs(directory, exist_ok=True)
258
+ for doc in documents:
259
+ with requests.get(doc["url"], stream=True,timeout=1000,verify=False) as r:
260
+ r.raise_for_status()
261
+ with open(directory + "/" + doc["fileName"], 'wb') as f:
262
+ for chunk in r.iter_content(chunk_size=8192):
263
+ f.write(chunk)
264
+ f.close()
265
+
266
+
267
+ def getLabels(self,code:str=None):
268
+ """
269
+ List all labels used in an assetmodel instance, or the list of all labels of a given node
270
+
271
+ Args:
272
+ code (Optional): The value of the code property for the node to get labels for
273
+ Returns:
274
+ A list of all node labels/types present in the model, or, if specified, for a node
275
+ """
276
+ if code is None:
277
+ args = {"q": "call db.labels()"}
278
+ else:
279
+ args = {"q": "match (n:EI_CURRENT {code: '" + code + "'}) return labels(n)"}
280
+ response = self._doJsonCypherRequest("EXECUTE",args)
281
+
282
+ labels = []
283
+ if code is None:
284
+ for label in response:
285
+ labels.append(label["label"])
286
+ else:
287
+ labels = response[0]['labels(n)']
288
+
289
+ return labels
290
+
291
+ def getRelatedEvents(self, node:Union[str,list], start:Union[str,int,float,datetime]="24 hours ago", end:Union[str,int,float,datetime]="now", limit:int=1000, output:str="json", directory:str=None):
292
+ """
293
+ Return all Events related to nodes via the Common Menu API.
294
+
295
+ Args:
296
+ node: The name of the node to query documents for
297
+ start: Timestamp of beginning of time window to search for events, also accepts strings like "30 mins ago"
298
+ end: Timestamp of end of time window to search for events
299
+ output (Optional): The format in which to return the data. Accepts one of: "raw" - The raw json returned by the API; "json" - A processed version of the json response; "df" - A formatted pandas dataframe object; "download" - Downloads the files to a local directory"
300
+ directory (Optional): Name and path to the directory created/used for downloaded documents. If omitted, will download files to current directory. Has no effect unless output is "download".
301
+
302
+ Returns:
303
+ The set of all documents related to the nodes, the format is dependent on the output parameter. If output is "download", it returns instead the files themselves
304
+
305
+ Raises:
306
+ KeyError: Raises an exception
307
+
308
+ """
309
+ nodes = force_list(node)
310
+ results = []
311
+ events = []
312
+ for node in nodes:
313
+ args = {"asset": node, "start": start, "end": end, "limit": limit}
314
+ response = self._doJsonCommonMenuRequest("events", args)
315
+ results.append(response)
316
+ events.append(response["events"])
317
+
318
+ if events == []:
319
+ return
320
+
321
+
322
+ if output == "raw":
323
+ return results
324
+ if output == "json":
325
+ return events[0]
326
+ if output == "df":
327
+ return pd.json_normalize(events[0])
328
+
329
+ def getProperties(self, nodes:Union[str,list], output="json"):
330
+ """
331
+ Return all properties of a node via the Assetmodel API
332
+
333
+ Args:
334
+ node: The name of the node to return properties of
335
+ output:
336
+
337
+ Returns:
338
+ A Json containing all nodes with a relation to any node that meets the criteria, and their relationship type.
339
+
340
+ Raises:
341
+ KeyError: Raises an exception
342
+
343
+ """
344
+ nodes = force_list(nodes)
345
+ results = []
346
+ properties = []
347
+ for node in nodes:
348
+ args = {}
349
+ args["asset"] = node
350
+ response = self._doJsonCommonMenuRequest("properties", args)
351
+ results.append(response)
352
+ properties.append(response["properties"])
353
+
354
+ if output == "raw":
355
+ return results
356
+ if output == "json":
357
+ return properties
358
+ if output == "df":
359
+ data = list(map(parse_properties, properties))
360
+ return pd.DataFrame(data,nodes)
361
+
362
+
363
+ def getMatchingNodes(self,prop:str,node:str,exact:bool=False):
364
+ """
365
+ Return all properties of matching nodes via a cypher query response
366
+
367
+ Args:
368
+ prop: The property on which to match
369
+ match: A list of nodes to return properties for
370
+ exact (Optional): Whether to only return nodes where the prop is equal to match, or nodes where prop contains match. Defaults to False
371
+
372
+ Returns:
373
+ A Json containing all nodes that contains the criteria.
374
+
375
+ Raises:
376
+ KeyError: Raises an exception
377
+ """
378
+
379
+ args = {}
380
+ if exact:
381
+ matchStatement = "n.%s = '%s'" % (prop,node)
382
+ else:
383
+ matchStatement = "n.%s contains '%s'" % (prop,node)
384
+ args['q'] = 'MATCH (n) WHERE %s RETURN n' % matchStatement
385
+
386
+ return self._doJsonCypherRequest("execute", args)
387
+
388
+ def getRelatedAssetsCypher(self, prop, nodes, exact: bool = False, relation=None):
389
+ """
390
+ Return all assets directly related to a given asset.
391
+
392
+ Args:
393
+ prop: The property on which to match a node
394
+ nodes: The value of the property to match
395
+ exact: Whether or not to only to apply to assets exactly matching value of node (Defaults to False)
396
+ relation: Specify a required relationship type for returned nodes
397
+
398
+ Returns:
399
+ A Json containing all nodes with a relation to any node that meets the criteria, and their relationship type.
400
+
401
+ Raises:
402
+ KeyError: Raises an exception
403
+
404
+ """
405
+ ret = []
406
+ exact = True
407
+ for node in force_list(nodes):
408
+ args = {}
409
+ if relation is not None: relation = ":" + relation
410
+ if exact:
411
+ matchStatement = "n.%s = '%s'" % (prop, node)
412
+ else:
413
+ matchStatement = "n.%s contains '%s'" % (prop, node)
414
+ args['q'] = 'MATCH (n)-[r%s]-(m:AssetObject) WHERE %s RETURN m' % (relation, matchStatement)
415
+
416
+ return list(map(cypherRespMap, self._doJsonCypherRequest("execute", args))) # Func was map of k -> k["m"]
417
+
418
+ def get_assetmodel(eigenserver:EigenServer=None):
419
+ """
420
+ Connect to Assetmodel of eigenserver. If eigenserver is not provided this will default to the EIGENSERVER environmental variable
421
+
422
+ Args:
423
+ eigenserver: An instance of EigenServer() to query
424
+
425
+ Returns:
426
+ An object defining a connection to the AssetModel
427
+ """
428
+ if eigenserver is None:
429
+ eigenserver = get_default_server()
430
+ elif type(eigenserver) == str:
431
+ eigenserver = EigenServer(eigenserver)
432
+
433
+ return AssetModel(eigenserver.getEigenServerUrl() + "ei-applet" + "/", eigenserver.auth)
eigeningenuity/auth.py ADDED
@@ -0,0 +1,178 @@
1
+ import os, msal, atexit, keyring
2
+ from cryptography.fernet import Fernet
3
+ from getpass import getuser
4
+ import eigeningenuity.settings as settings
5
+
6
+ cache = msal.SerializableTokenCache()
7
+ url = None
8
+
9
+ def encrypt(data,key):
10
+ cipher_suite = Fernet(key)
11
+ encrypted_data = cipher_suite.encrypt(data.encode())
12
+ return encrypted_data
13
+
14
+ def decrypt(data,key):
15
+ cipher_suite = Fernet(key)
16
+ decrypted_data = cipher_suite.decrypt(data).decode()
17
+ return decrypted_data
18
+
19
+ def _authenticate_azure_user(baseurl):
20
+ global url
21
+ url = baseurl
22
+ if settings._token_cache_enabled_:
23
+ global cache
24
+ try:
25
+ encryptionKey = keyring.get_password("eigeningenuity","python")
26
+ except:
27
+ pass
28
+
29
+ if not os.path.exists(os.path.dirname(__file__) + '/.azure'):
30
+ os.mkdir(os.path.dirname(__file__) + "/.azure")
31
+
32
+ if os.path.exists(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin"):
33
+ encryptedToken = open(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin", "rb").read()
34
+ if encryptedToken != b'':
35
+ cache.deserialize(decrypt(encryptedToken,encryptionKey))
36
+
37
+ encryptionKey = Fernet.generate_key().decode('utf-8')
38
+
39
+ atexit.register(lambda:
40
+ open(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin", "wb").write(encrypt(cache.serialize(),encryptionKey)) and keyring.set_password("eigeningenuity","python",encryptionKey)
41
+ if cache.has_state_changed else None
42
+ )
43
+
44
+ tenant_id = settings._azure_tenant_id_
45
+ client_id = settings._azure_client_id_
46
+ authority = f'https://login.microsoftonline.com/{tenant_id}'
47
+ scope=[f"{baseurl}/user_impersonation"]
48
+
49
+ app = msal.PublicClientApplication(
50
+ client_id=client_id,
51
+ authority=authority,
52
+ token_cache=cache
53
+ )
54
+
55
+ result=None
56
+
57
+ # We now check the cache to see
58
+ # whether we already have some accounts that the end user already used to sign in before.
59
+ accounts = app.get_accounts()
60
+ if accounts:
61
+ account = 0
62
+ # If so, you could then somehow display these accounts and let end user choose
63
+ if len(accounts) >= 2:
64
+ print("Found Multiple Users in Cache")
65
+ while True:
66
+ for idx,a in enumerate(accounts):
67
+ print(f'{idx}: {a["username"]}')
68
+ try:
69
+ account = int(input("Enter the number of the account you want to use:\n"))
70
+ if account not in list(range(len(accounts))):
71
+ print("That is not a valid option!")
72
+ else:
73
+ break
74
+ except:
75
+ print("That is not a valid option!")
76
+
77
+ # Assuming the end user chose this one
78
+ chosen = accounts[account]
79
+ # Now let's try to find a token in cache for this account
80
+ result = app.acquire_token_silent(scope, account=chosen)
81
+
82
+
83
+ if not result:
84
+ # So no suitable token exists in cache. Let's get a new one from Azure AD.
85
+ settings.clear_auth_token_cache()
86
+ result = app.acquire_token_interactive(scope,auth_uri_callback=_backup_auth_azure_user)
87
+
88
+ if "access_token" in result:
89
+ access_token = (result["access_token"]) # Yay!
90
+ else:
91
+ print(result.get("error"))
92
+ print(result.get("error_description"))
93
+ print(result.get("correlation_id")) # You may need this when reporting a bug
94
+
95
+ # Make requests to the Java API using the obtained access token
96
+ return {
97
+ 'Authorization': f'Bearer {access_token}',
98
+ 'Accept': 'application/json',
99
+ 'Content-Type': 'application/json'
100
+ }
101
+
102
+
103
+ def _backup_auth_azure_user(_uri):
104
+ global url
105
+ baseurl = url
106
+ if settings._token_cache_enabled_:
107
+ global cache
108
+ try:
109
+ encryptionKey = keyring.get_password("eigeningenuity","python")
110
+ except:
111
+ pass
112
+
113
+ if not os.path.exists(os.path.dirname(__file__) + '/.azure'):
114
+ os.mkdir(os.path.dirname(__file__) + "/.azure")
115
+
116
+ if os.path.exists(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin"):
117
+ encryptedToken = open(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin", "rb").read()
118
+ if encryptedToken != b'':
119
+ cache.deserialize(decrypt(encryptedToken,encryptionKey))
120
+
121
+ encryptionKey = Fernet.generate_key().decode('utf-8')
122
+
123
+ atexit.register(lambda:
124
+ open(os.path.dirname(__file__) + f"/.azure/{getuser()}_cache.bin", "wb").write(encrypt(cache.serialize(),encryptionKey)) and keyring.set_password("eigeningenuity","python",encryptionKey)
125
+ if cache.has_state_changed else None
126
+ )
127
+
128
+
129
+ authority = f'https://login.microsoftonline.com/{settings._azure_tenant_id_}'
130
+ scope=[f"{baseurl}/user_impersonation"]
131
+ client_id = settings._azure_client_id_
132
+
133
+
134
+ app = msal.PublicClientApplication(
135
+ client_id=client_id,
136
+ authority=authority,
137
+ token_cache=cache
138
+ )
139
+
140
+ result=None
141
+
142
+ # We now check the cache to see
143
+ # whether we already have some accounts that the end user already used to sign in before.
144
+ accounts = app.get_accounts()
145
+ if accounts:
146
+ account = 0
147
+ # If so, you could then somehow display these accounts and let end user choose
148
+ if len(accounts) >= 2:
149
+ print("Found Multiple Users in Cache")
150
+ while True:
151
+ for idx,a in enumerate(accounts):
152
+ print(f'{idx}: {a["username"]}')
153
+ try:
154
+ account = int(input("Enter the number of the account you want to use:\n"))
155
+ if account not in list(range(len(accounts))):
156
+ print("That is not a valid option!")
157
+ else:
158
+ break
159
+ except:
160
+ print("That is not a valid option!")
161
+
162
+ # Assuming the end user chose this one
163
+ chosen = accounts[account]
164
+ # Now let's try to find a token in cache for this account
165
+ result = app.acquire_token_silent(scope, account=chosen)
166
+
167
+
168
+ if not result:
169
+ # So no suitable token exists in cache. Let's get a new one from Azure AD.
170
+ flow = app.initiate_device_flow(scopes=scope)
171
+ print(flow["message"])
172
+ print("Please navigate to:", flow["verification_uri"])
173
+
174
+ result = app.acquire_token_by_device_flow(flow)
175
+
176
+ # Make requests to the Java API using the obtained access token
177
+ return result
178
+