import json import os import requests import datetime from dotenv import load_dotenv filename = "config.json" load_dotenv() sslCertLocation = os.getenv('CERT_LOCATION', '') def save_properties_json(filename, data): with open(filename, 'w') as f: json.dump(data, f) def load_properties_json(filename): try: with open(filename, 'r') as f: return json.load(f) except FileNotFoundError: return {} # Request a new token if the existing token has expired def getAuthToken(clientId = "", clientSecret = "", address = "") -> str: payload = json.dumps( { "client_id": clientId, "client_secret": clientSecret, "grant_type": "client_credentials" } ) headers = { "Content-Type": "application/json", } response = sendHttpRequest(data = payload, header = headers, method = "POST", address = address, endpoint = "/oauth2/token") json_data = response.text json_object = json.loads(json_data) if response.status_code != 200: print("Auth failed!") return "" # print("Saving new token") json_object["access_token_created_at"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") save_properties_json(filename, json_object) return json_object["access_token"] def sendHttpRequest(data = "", files = "", params = "", header = "", method = "", address = "", endpoint = "", stream = False) -> bytearray: protocol = "https" if os.getenv('HORIZON_API_SECURE', 'false').lower() == 'true': protocol = "http" url = f"{protocol}://{address}" response = requests.request( # Set verify to False to ignore the SSL cert, otherwise provide a path (here, an env var) method=method, url=f"{url}{endpoint}", headers=header, data=data, files=files, params=params, stream=stream, verify=f"{sslCertLocation}" # method=method, url=f"{url}{endpoint}", headers=header, data=data, files=files, params=params, stream=stream, verify=os.getenv('WELLPOINT_CA_BUNDLE') ) if response.status_code != 200: print(f"HTTP request failed. Endpoint {endpoint} Error: {response.status_code}\n") return bytearray() else: # print(f"Returning {response}") return response