-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
176 lines (137 loc) · 4.41 KB
/
client.py
File metadata and controls
176 lines (137 loc) · 4.41 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
import logging
from datetime import datetime, timedelta, timezone
from functools import wraps
from urllib.parse import urljoin
from uuid import uuid4
import jwt
import requests
from requests import HTTPError
logger = logging.getLogger(__name__)
class FinOpsError(Exception):
pass
class FinOpsHttpError(FinOpsError):
def __init__(self, status_code: int, content: str):
self.status_code = status_code
self.content = content
super().__init__(f"{self.status_code} - {self.content}")
class FinOpsNotFoundError(FinOpsHttpError):
def __init__(self, content):
super().__init__(404, content)
def wrap_http_error(func):
@wraps(func)
def _wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except HTTPError as e:
if e.response.status_code == 404:
raise FinOpsNotFoundError(e.response.json())
else:
raise FinOpsHttpError(e.response.status_code, e.response.json())
return _wrapper
class FinOpsClient:
def __init__(self, base_url, sub, secret):
self._sub = sub
self._secret = secret
self._api_base_url = base_url
self._jwt = None
@wrap_http_error
def get_employee(self, email):
headers = self._get_headers()
response = requests.get(
urljoin(self._api_base_url, f"/ops/v1/employees/{email}"),
headers=headers,
)
response.raise_for_status()
return response.json()
@wrap_http_error
def create_employee(self, email, name):
headers = self._get_headers()
response = requests.post(
urljoin(self._api_base_url, "/ops/v1/employees"),
headers=headers,
json={
"email": email,
"display_name": name,
},
)
response.raise_for_status()
return response.json()
@wrap_http_error
def create_organization(
self,
name,
currency,
billing_currency,
external_id,
user_id,
):
headers = self._get_headers()
response = requests.post(
urljoin(self._api_base_url, "/ops/v1/organizations"),
headers=headers,
json={
"name": name,
"currency": currency,
"billing_currency": billing_currency,
"operations_external_id": external_id,
"user_id": user_id,
},
)
response.raise_for_status()
return response.json()
@wrap_http_error
def get_organization_by_external_id(self, agreement_id):
headers = self._get_headers()
rql_filter = f"operations_external_id={agreement_id}"
response = requests.get(
urljoin(
self._api_base_url,
f"/ops/v1/organizations?&{rql_filter}&limit=1",
),
headers=headers,
)
response.raise_for_status()
return response.json()["items"][0]
def _get_headers(self):
return {
"Authorization": f"Bearer {self._get_auth_token()}",
"Accept": "application/json",
"Content-Type": "application/json",
"X-Request-Id": str(uuid4()),
}
def _get_auth_token(self):
if not self._jwt or self._is_token_expired():
now = datetime.now(tz=timezone.utc)
self._jwt = jwt.encode(
{
"sub": self._sub,
"exp": now + timedelta(minutes=5),
"nbf": now,
"iat": now,
},
self._secret,
algorithm="HS256",
)
return self._jwt
def _is_token_expired(self):
try:
jwt.decode(self._jwt, self._secret, algorithms=["HS256"])
return False
except jwt.ExpiredSignatureError:
return True
_FFC_CLIENT = None
def get_ffc_client():
"""
Returns an instance of the `FinOpsClient`.
Returns:
FinOpsClient: An instance of the `FinOpsClient`.
"""
from django.conf import settings
global _FFC_CLIENT
if not _FFC_CLIENT:
_FFC_CLIENT = FinOpsClient(
settings.EXTENSION_CONFIG["FFC_OPERATIONS_API_BASE_URL"],
settings.EXTENSION_CONFIG["FFC_SUB"],
settings.EXTENSION_CONFIG["FFC_OPERATIONS_SECRET"],
)
return _FFC_CLIENT