-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.py
92 lines (81 loc) · 2.32 KB
/
library.py
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
import requests
import jwt
apiURL = ''
rsession = requests.Session()
def is_token_exp(token):
now = datetime.utcnow().replace(tzinfo=timezone.utc).timestamp()
decode = jwt.decode(token, verify=False)
exp = decode['exp']
if (exp - now) < 600:
return True
else:
return False
def session_key(api_key):
head = {'Content-Type': 'application/json'}
body = '{"data": {"api_key":"' + api_key + '"} }'
url = apiURL + '/v2/api_auth'
response = rsession.put(url, headers=head, data=body, timeout=10)
if response.json()['status'] == 'success':
sk = response.json()['auth_token']
return sk
else:
raise RuntimeError(
'An error occurred: ' +
response.json()['error'] +
', ' +
response.json()['data']['message']
)
def validate_token(api_key, token):
head = {
'Accept': 'application/json',
'X-Auth-Token': token,
}
url = apiURL + '/v2/token_auth'
response = rsession.get(url, headers=head, timeout=10)
if response.json()['status'] == 'success':
return token
else:
new_token = session_key(api_key)
return new_token
def GetAccounts(
token,
accID,
):
head = {
'Accept': 'application/json',
'X-Auth-Token': token,
}
url = apiURL + '/v2/accounts/' + accID + '/descendants'
# ?auth_token=' + token
response = rsession.get(url, headers=head, timeout=10)
accounts = []
i = 0
while i < response.json()['page_size']:
accounts.append(
{
'account_id':response.json()['data'][i]['id'],
'account_name':response.json()['data'][i]['name'],
'account_realm':response.json()['data'][i]['realm'],
'parent_id':response.json()['data'][i]['tree'][-1],
}
)
i += 1
return accounts
def GetNumbers(
token,
accID,
numberStatus='in_service',
):
head = {
'Accept': 'application/json',
'X-Auth-Token': token,
}
url = apiURL + '/v2/accounts/' + accID + '/phone_numbers'
response = rsession.get(url, headers=head, timeout=10)
numbers = []
try:
for x in response.json()['data']['numbers']:
numbers.append(x)
return numbers
except KeyError:
return None