File size: 2,305 Bytes
0021b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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