neris-api-client 0.1.1__tar.gz
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-0.1.1/LICENSE +21 -0
- neris_api_client-0.1.1/PKG-INFO +38 -0
- neris_api_client-0.1.1/README.md +19 -0
- neris_api_client-0.1.1/pyproject.toml +29 -0
- neris_api_client-0.1.1/setup.cfg +4 -0
- neris_api_client-0.1.1/src/neris_api_client/__init__.py +1 -0
- neris_api_client-0.1.1/src/neris_api_client/client.py +258 -0
- neris_api_client-0.1.1/src/neris_api_client/models.py +5426 -0
- neris_api_client-0.1.1/src/neris_api_client.egg-info/PKG-INFO +38 -0
- neris_api_client-0.1.1/src/neris_api_client.egg-info/SOURCES.txt +11 -0
- neris_api_client-0.1.1/src/neris_api_client.egg-info/dependency_links.txt +1 -0
- neris_api_client-0.1.1/src/neris_api_client.egg-info/requires.txt +5 -0
- neris_api_client-0.1.1/src/neris_api_client.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Underwriters Laboratories, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: neris_api_client
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: NERIS API Client
|
|
5
|
+
Author-email: Ben Coleman <ben.coleman@ul.org>
|
|
6
|
+
Project-URL: Homepage, https://github.com/ulfsri/neris
|
|
7
|
+
Project-URL: Issues, https://github.com/ulfsri/neris/issues
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.8
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: boto3
|
|
15
|
+
Requires-Dist: PyJWT
|
|
16
|
+
Requires-Dist: requests
|
|
17
|
+
Requires-Dist: pydantic>=2
|
|
18
|
+
Requires-Dist: typing_extensions
|
|
19
|
+
|
|
20
|
+
# NERIS API Client
|
|
21
|
+
|
|
22
|
+
A Python class to interact with the NERIS API programmatically.
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
The client requires a username and password for authentication and authorization of requests unless the `env` argument is set to `local`
|
|
26
|
+
at instantiation. The `local` environment is intended for development use on local machines and bypasses auth.
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
from neris_api_client import NerisApiClient
|
|
30
|
+
|
|
31
|
+
client = NerisApiClient(username="neris.user", password="*******", env="dev")
|
|
32
|
+
|
|
33
|
+
# Get an entity
|
|
34
|
+
entity = client.get_entity("FD24027240")
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
API auth tokens are cached locally in `./.token_cache`. If there are auth issues first try instantiating the client with `use_cache=False`
|
|
38
|
+
keyword argument or deleting the token cache.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# NERIS API Client
|
|
2
|
+
|
|
3
|
+
A Python class to interact with the NERIS API programmatically.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
The client requires a username and password for authentication and authorization of requests unless the `env` argument is set to `local`
|
|
7
|
+
at instantiation. The `local` environment is intended for development use on local machines and bypasses auth.
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from neris_api_client import NerisApiClient
|
|
11
|
+
|
|
12
|
+
client = NerisApiClient(username="neris.user", password="*******", env="dev")
|
|
13
|
+
|
|
14
|
+
# Get an entity
|
|
15
|
+
entity = client.get_entity("FD24027240")
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
API auth tokens are cached locally in `./.token_cache`. If there are auth issues first try instantiating the client with `use_cache=False`
|
|
19
|
+
keyword argument or deleting the token cache.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "neris_api_client"
|
|
7
|
+
version = "0.1.1"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name="Ben Coleman", email="ben.coleman@ul.org" },
|
|
10
|
+
]
|
|
11
|
+
description = "NERIS API Client"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.8"
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Operating System :: OS Independent",
|
|
18
|
+
]
|
|
19
|
+
dependencies = [
|
|
20
|
+
"boto3",
|
|
21
|
+
"PyJWT",
|
|
22
|
+
"requests",
|
|
23
|
+
"pydantic>=2",
|
|
24
|
+
"typing_extensions",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/ulfsri/neris"
|
|
29
|
+
Issues = "https://github.com/ulfsri/neris/issues"
|
|
@@ -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
|
+
)
|