neris-api-client 0.1.1__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.
- neris_api_client/__init__.py +1 -0
- neris_api_client/client.py +258 -0
- neris_api_client/models.py +5426 -0
- neris_api_client-0.1.1.dist-info/LICENSE +21 -0
- neris_api_client-0.1.1.dist-info/METADATA +38 -0
- neris_api_client-0.1.1.dist-info/RECORD +8 -0
- neris_api_client-0.1.1.dist-info/WHEEL +5 -0
- neris_api_client-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .client import *
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import jwt
|
|
2
|
+
import json
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
from typing import List, Optional, Dict, Any, Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from datetime import datetime, timedelta
|
|
8
|
+
|
|
9
|
+
import boto3
|
|
10
|
+
import requests
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
|
|
13
|
+
from .models import (
|
|
14
|
+
IncidentPayload,
|
|
15
|
+
CreateDepartmentPayload,
|
|
16
|
+
DepartmentPayload,
|
|
17
|
+
CreateUserPayload,
|
|
18
|
+
UpdateUserPayload,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = ("NerisApiClient",)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Environment(str, Enum):
|
|
25
|
+
DEV = "dev"
|
|
26
|
+
PROD = "prod"
|
|
27
|
+
LOCAL = "local"
|
|
28
|
+
TEST = "test"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
BASE_URLS = {
|
|
32
|
+
Environment.LOCAL: "http://localhost:8000",
|
|
33
|
+
Environment.DEV: "https://api-dev.neris.fsri.org/v1",
|
|
34
|
+
Environment.PROD: "https://api.neris.fsri.org/v1",
|
|
35
|
+
Environment.TEST: "https://api-test.neris.fsri.org/v1",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
COGNITO_CLIENT_CONFIG_URL = (
|
|
39
|
+
"https://neris-{env}-public.s3.us-east-2.amazonaws.com/cognito_config.json"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _NerisApiClient:
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
username: str = "",
|
|
47
|
+
password: str = "",
|
|
48
|
+
env: Environment = Environment.LOCAL,
|
|
49
|
+
use_cache: bool = True,
|
|
50
|
+
):
|
|
51
|
+
self._username = username
|
|
52
|
+
self._password = password
|
|
53
|
+
self._base_url = BASE_URLS[env]
|
|
54
|
+
self._env = env
|
|
55
|
+
self._use_cache = use_cache
|
|
56
|
+
|
|
57
|
+
self._access_token: str = None
|
|
58
|
+
self._access_token_exp: datetime = None
|
|
59
|
+
self._refresh_token: str = None
|
|
60
|
+
self._id_token: str = None
|
|
61
|
+
self._id_token_exp: datetime = None
|
|
62
|
+
self._cognito_config = None
|
|
63
|
+
self._session: requests.Session = requests.Session()
|
|
64
|
+
|
|
65
|
+
# Don't mess with auth on localhost
|
|
66
|
+
if env == Environment.LOCAL:
|
|
67
|
+
# Non-existent auth token never expires
|
|
68
|
+
self._use_cache = False
|
|
69
|
+
self._access_token_exp = datetime.now() + timedelta(weeks=52)
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
self._cognito = boto3.client("cognito-idp")
|
|
73
|
+
|
|
74
|
+
self._token_cache_path = Path("./.token_cache")
|
|
75
|
+
self._access_token_cache_path = self._token_cache_path / "access_token"
|
|
76
|
+
self._refresh_token_cache_path = self._token_cache_path / "refresh_token"
|
|
77
|
+
self._id_token_cache_path = self._token_cache_path / "id_token"
|
|
78
|
+
self._cognito_config_cache_path = self._token_cache_path / "cognito_config.json"
|
|
79
|
+
|
|
80
|
+
if self._use_cache:
|
|
81
|
+
self._read_token_cache()
|
|
82
|
+
|
|
83
|
+
if self._access_token:
|
|
84
|
+
self._set_token_exp()
|
|
85
|
+
|
|
86
|
+
if not self._access_token:
|
|
87
|
+
self._initiate_auth()
|
|
88
|
+
|
|
89
|
+
def _fetch_cognito_config(f: Callable) -> Callable:
|
|
90
|
+
def fetch_cognito_config(self):
|
|
91
|
+
if self._cognito_config is None:
|
|
92
|
+
self._cognito_config = requests.get(
|
|
93
|
+
COGNITO_CLIENT_CONFIG_URL.format(env=self._env)
|
|
94
|
+
).json()
|
|
95
|
+
return f(self)
|
|
96
|
+
|
|
97
|
+
return fetch_cognito_config
|
|
98
|
+
|
|
99
|
+
@_fetch_cognito_config
|
|
100
|
+
def _initiate_auth(self) -> None:
|
|
101
|
+
res = self._cognito.initiate_auth(
|
|
102
|
+
AuthFlow="USER_PASSWORD_AUTH",
|
|
103
|
+
AuthParameters={"USERNAME": self._username, "PASSWORD": self._password},
|
|
104
|
+
ClientId=self._cognito_config["client_id"],
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
self._access_token = res["AuthenticationResult"]["AccessToken"]
|
|
108
|
+
self._refresh_token = res["AuthenticationResult"]["RefreshToken"]
|
|
109
|
+
self._id_token = res["AuthenticationResult"]["IdToken"]
|
|
110
|
+
|
|
111
|
+
self._set_token_exp()
|
|
112
|
+
|
|
113
|
+
if self._use_cache:
|
|
114
|
+
self._write_token_cache()
|
|
115
|
+
|
|
116
|
+
@_fetch_cognito_config
|
|
117
|
+
def _refresh_auth(self) -> None:
|
|
118
|
+
res = self._cognito.initiate_auth(
|
|
119
|
+
AuthFlow="REFRESH_TOKEN_AUTH",
|
|
120
|
+
AuthParameters={"REFRESH_TOKEN": self._refresh_token},
|
|
121
|
+
ClientId=self._cognito_config["client_id"],
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
self._access_token = res["AuthenticationResult"]["AccessToken"]
|
|
125
|
+
self._id_token = res["AuthenticationResult"]["IdToken"]
|
|
126
|
+
|
|
127
|
+
self._set_token_exp()
|
|
128
|
+
|
|
129
|
+
self._write_token_cache()
|
|
130
|
+
|
|
131
|
+
def _set_token_exp(self):
|
|
132
|
+
self._access_token_exp = datetime.fromtimestamp(
|
|
133
|
+
self._decode_token(self._access_token)["exp"]
|
|
134
|
+
)
|
|
135
|
+
self._id_token_exp = datetime.fromtimestamp(
|
|
136
|
+
self._decode_token(self._id_token)["exp"]
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def _read_token_cache(self):
|
|
140
|
+
if self._access_token_cache_path.exists():
|
|
141
|
+
self._access_token = self._access_token_cache_path.read_text()
|
|
142
|
+
if self._refresh_token_cache_path.exists():
|
|
143
|
+
self._refresh_token = self._refresh_token_cache_path.read_text()
|
|
144
|
+
if self._id_token_cache_path.exists():
|
|
145
|
+
self._id_token = self._id_token_cache_path.read_text()
|
|
146
|
+
if self._cognito_config_cache_path.exists():
|
|
147
|
+
self._cognito_config = json.loads(
|
|
148
|
+
self._cognito_config_cache_path.read_text()
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
def _write_token_cache(self):
|
|
152
|
+
self._token_cache_path.mkdir(exist_ok=True)
|
|
153
|
+
self._access_token_cache_path.write_text(self._access_token)
|
|
154
|
+
self._refresh_token_cache_path.write_text(self._refresh_token)
|
|
155
|
+
self._id_token_cache_path.write_text(self._id_token)
|
|
156
|
+
self._cognito_config_cache_path.write_text(json.dumps(self._cognito_config))
|
|
157
|
+
|
|
158
|
+
@staticmethod
|
|
159
|
+
def _decode_token(token: str, verify: bool = False):
|
|
160
|
+
return jwt.decode(token, options={"verify_signature": verify})
|
|
161
|
+
|
|
162
|
+
def _call(
|
|
163
|
+
self,
|
|
164
|
+
method: str,
|
|
165
|
+
path: str,
|
|
166
|
+
data: Optional[str | Dict[str, Any]] = None,
|
|
167
|
+
params: Optional[Dict[str, Any]] = None,
|
|
168
|
+
model: Optional[BaseModel] = None,
|
|
169
|
+
):
|
|
170
|
+
if self._access_token_exp - datetime.now() <= timedelta(seconds=0):
|
|
171
|
+
try:
|
|
172
|
+
self._refresh_auth()
|
|
173
|
+
except:
|
|
174
|
+
self._initiate_auth()
|
|
175
|
+
|
|
176
|
+
if self._env != Environment.LOCAL:
|
|
177
|
+
self._session.headers.update(
|
|
178
|
+
{"Authorization": f"Bearer {self._access_token}"}
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if model:
|
|
182
|
+
if isinstance(data, str):
|
|
183
|
+
data = model.model_validate_json(data).model_dump(
|
|
184
|
+
mode="json", by_alias=True
|
|
185
|
+
)
|
|
186
|
+
if isinstance(data, dict):
|
|
187
|
+
data = model.model_validate(data).model_dump(mode="json", by_alias=True)
|
|
188
|
+
|
|
189
|
+
res = getattr(self._session, method)(
|
|
190
|
+
f"{self._base_url}{path}", json=data, params=params
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
try:
|
|
194
|
+
res.raise_for_status()
|
|
195
|
+
except requests.exceptions.HTTPError as e:
|
|
196
|
+
try:
|
|
197
|
+
e.args = e.args + (e.response.json(),)
|
|
198
|
+
raise e
|
|
199
|
+
except requests.exceptions.JSONDecodeError as f:
|
|
200
|
+
e.args = e.args + (e.response.text,)
|
|
201
|
+
raise e
|
|
202
|
+
|
|
203
|
+
return res.json()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class NerisApiClient(_NerisApiClient):
|
|
207
|
+
def health(self):
|
|
208
|
+
return self._call("get", "/health")
|
|
209
|
+
|
|
210
|
+
def get_entity(self, neris_id: str) -> Dict[str, Any]:
|
|
211
|
+
return self._call("get", f"/entity/{neris_id}")
|
|
212
|
+
|
|
213
|
+
def create_entity(self, body: str | Dict[str, Any]) -> Dict[str, Any]:
|
|
214
|
+
return self._call("post", "/entity/", body, model=CreateDepartmentPayload)
|
|
215
|
+
|
|
216
|
+
def update_entity(
|
|
217
|
+
self, neris_id: str, body: str | Dict[str, Any]
|
|
218
|
+
) -> Dict[str, Any]:
|
|
219
|
+
return self._call("put", f"/entity/{neris_id}", body, model=DepartmentPayload)
|
|
220
|
+
|
|
221
|
+
def get_user(self, sub: str | UUID) -> Dict[str, Any]:
|
|
222
|
+
return self._call("get", f"/user/{sub}")
|
|
223
|
+
|
|
224
|
+
def create_user(self, body: str | Dict[str, Any]) -> Dict[str, Any]:
|
|
225
|
+
return self._call("post", "/user", body, model=CreateUserPayload)
|
|
226
|
+
|
|
227
|
+
def update_user(
|
|
228
|
+
self, sub: str | UUID, body: str | Dict[str, Any]
|
|
229
|
+
) -> Dict[str, Any]:
|
|
230
|
+
return self._call("put", f"/user/{sub}", body, model=UpdateUserPayload)
|
|
231
|
+
|
|
232
|
+
def delete_user(self, sub: str | UUID) -> None:
|
|
233
|
+
self._call("delete", f"/user/{sub}")
|
|
234
|
+
|
|
235
|
+
def create_user_entity_membership(self, sub: str | UUID, neris_id: str) -> None:
|
|
236
|
+
self._call("post", f"/user/{sub}/user_entity_membership/{neris_id}")
|
|
237
|
+
|
|
238
|
+
def delete_user_entity_membership(self, sub: str | UUID, neris_id: str) -> None:
|
|
239
|
+
self._call("delete", f"/user/{sub}/user_entity_membership/{neris_id}")
|
|
240
|
+
|
|
241
|
+
def update_user_entity_activation(
|
|
242
|
+
self, sub: str | UUID, neris_id: str, active: bool
|
|
243
|
+
) -> None:
|
|
244
|
+
self._call(
|
|
245
|
+
"put",
|
|
246
|
+
f"/user/{sub}/user_entity_activation/{neris_id}",
|
|
247
|
+
data={"active": active},
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
def list_user_entity_memberships(self, sub: str | UUID) -> List[Dict[str, Any]]:
|
|
251
|
+
return self._call("get", f"/user/{sub}/user_entity_membership")
|
|
252
|
+
|
|
253
|
+
def create_incident(
|
|
254
|
+
self, neris_id: str, body: str | Dict[str, Any]
|
|
255
|
+
) -> Dict[str, Any]:
|
|
256
|
+
return self._call(
|
|
257
|
+
"post", f"/incident/{neris_id}", data=body, model=IncidentPayload
|
|
258
|
+
)
|