PyFlumeNG 0.9.0__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.
- pyflume/__init__.py +97 -0
- pyflume/auth.py +390 -0
- pyflume/client.py +1385 -0
- pyflume/constants.py +31 -0
- pyflume/data.py +226 -0
- pyflume/devices.py +70 -0
- pyflume/errors.py +57 -0
- pyflume/leak.py +83 -0
- pyflume/models.py +681 -0
- pyflume/notifications.py +138 -0
- pyflume/py.typed +1 -0
- pyflume/rate_limit.py +52 -0
- pyflume/types.py +48 -0
- pyflume/usage.py +265 -0
- pyflume/utils.py +140 -0
- pyflumeng-0.9.0.dist-info/METADATA +149 -0
- pyflumeng-0.9.0.dist-info/RECORD +20 -0
- pyflumeng-0.9.0.dist-info/WHEEL +5 -0
- pyflumeng-0.9.0.dist-info/licenses/LICENSE +21 -0
- pyflumeng-0.9.0.dist-info/top_level.txt +1 -0
pyflume/__init__.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""PyFlumeNG: a complete Flume API client with portal capabilities."""
|
|
2
|
+
|
|
3
|
+
from .auth import ( # noqa: WPS300, F401
|
|
4
|
+
FlumeAuth,
|
|
5
|
+
FlumePortalAuth,
|
|
6
|
+
)
|
|
7
|
+
from .auth import (
|
|
8
|
+
FlumeAuth as PersonalAuth,
|
|
9
|
+
)
|
|
10
|
+
from .auth import (
|
|
11
|
+
FlumePortalAuth as PortalAuth,
|
|
12
|
+
)
|
|
13
|
+
from .client import FlumeClient # noqa: WPS300, F401
|
|
14
|
+
from .data import FlumeData # noqa: WPS300, F401
|
|
15
|
+
from .devices import FlumeDeviceList # noqa: WPS300, F401
|
|
16
|
+
from .errors import ( # noqa: WPS300, F401
|
|
17
|
+
FlumeAuthError,
|
|
18
|
+
FlumeCapabilityError,
|
|
19
|
+
FlumeError,
|
|
20
|
+
FlumeHTTPError,
|
|
21
|
+
FlumeRateLimitError,
|
|
22
|
+
)
|
|
23
|
+
from .leak import FlumeLeakList # noqa: WPS300, F401
|
|
24
|
+
from .models import ( # noqa: WPS300, F401
|
|
25
|
+
AccuracyResult,
|
|
26
|
+
ApiClient,
|
|
27
|
+
Budget,
|
|
28
|
+
Contact,
|
|
29
|
+
CurrentFlow,
|
|
30
|
+
Device,
|
|
31
|
+
DoNotAlertSchedule,
|
|
32
|
+
FlumeModel,
|
|
33
|
+
FlumeResponse,
|
|
34
|
+
Insurer,
|
|
35
|
+
Integration,
|
|
36
|
+
Leak,
|
|
37
|
+
Location,
|
|
38
|
+
LocationAccess,
|
|
39
|
+
LocationProfiles,
|
|
40
|
+
Notification,
|
|
41
|
+
ProService,
|
|
42
|
+
PurchaseOption,
|
|
43
|
+
QueryResult,
|
|
44
|
+
Span,
|
|
45
|
+
SpanType,
|
|
46
|
+
Subscription,
|
|
47
|
+
UsageAlert,
|
|
48
|
+
UsageAlertRule,
|
|
49
|
+
User,
|
|
50
|
+
)
|
|
51
|
+
from .notifications import FlumeNotificationList # noqa: WPS300, F401
|
|
52
|
+
from .rate_limit import RateLimitState # noqa: WPS300, F401
|
|
53
|
+
from .usage import FlumeUsageAlertList # noqa: WPS300, F401
|
|
54
|
+
|
|
55
|
+
__all__ = [
|
|
56
|
+
"FlumeAuth",
|
|
57
|
+
"PersonalAuth",
|
|
58
|
+
"FlumePortalAuth",
|
|
59
|
+
"PortalAuth",
|
|
60
|
+
"FlumeClient",
|
|
61
|
+
"FlumeData",
|
|
62
|
+
"FlumeDeviceList",
|
|
63
|
+
"FlumeLeakList",
|
|
64
|
+
"FlumeNotificationList",
|
|
65
|
+
"FlumeUsageAlertList",
|
|
66
|
+
"FlumeModel",
|
|
67
|
+
"FlumeResponse",
|
|
68
|
+
"User",
|
|
69
|
+
"Device",
|
|
70
|
+
"Location",
|
|
71
|
+
"LocationProfiles",
|
|
72
|
+
"Notification",
|
|
73
|
+
"UsageAlert",
|
|
74
|
+
"UsageAlertRule",
|
|
75
|
+
"Budget",
|
|
76
|
+
"Subscription",
|
|
77
|
+
"DoNotAlertSchedule",
|
|
78
|
+
"LocationAccess",
|
|
79
|
+
"Integration",
|
|
80
|
+
"Span",
|
|
81
|
+
"SpanType",
|
|
82
|
+
"Leak",
|
|
83
|
+
"CurrentFlow",
|
|
84
|
+
"QueryResult",
|
|
85
|
+
"PurchaseOption",
|
|
86
|
+
"Contact",
|
|
87
|
+
"Insurer",
|
|
88
|
+
"ApiClient",
|
|
89
|
+
"AccuracyResult",
|
|
90
|
+
"ProService",
|
|
91
|
+
"RateLimitState",
|
|
92
|
+
"FlumeError",
|
|
93
|
+
"FlumeAuthError",
|
|
94
|
+
"FlumeCapabilityError",
|
|
95
|
+
"FlumeHTTPError",
|
|
96
|
+
"FlumeRateLimitError",
|
|
97
|
+
]
|
pyflume/auth.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Authenticates to Flume API."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from datetime import datetime, timedelta, timezone
|
|
5
|
+
from typing import Any, ClassVar, Dict, FrozenSet, Mapping, Optional, cast
|
|
6
|
+
from urllib.parse import parse_qs, urlparse
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
import jwt # install pyjwt
|
|
10
|
+
from jwt.types import Options
|
|
11
|
+
from requests import Session
|
|
12
|
+
|
|
13
|
+
from .constants import ( # noqa: WPS300
|
|
14
|
+
DEFAULT_TIMEOUT,
|
|
15
|
+
PORTAL_API_URL,
|
|
16
|
+
PORTAL_CLIENT_ID,
|
|
17
|
+
PORTAL_OAUTH_AUTHORIZE_URL,
|
|
18
|
+
PORTAL_OAUTH_TOKEN_URL,
|
|
19
|
+
PORTAL_REDIRECT_URI,
|
|
20
|
+
URL_OAUTH_TOKEN,
|
|
21
|
+
)
|
|
22
|
+
from .rate_limit import RateLimitState # noqa: WPS300
|
|
23
|
+
from .types import FlumeToken, JSONDict, ResourceId # noqa: WPS300
|
|
24
|
+
from .utils import ( # noqa: WPS300
|
|
25
|
+
FlumeResponseError,
|
|
26
|
+
configure_logger,
|
|
27
|
+
flume_response_error,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# Configure logging
|
|
31
|
+
LOGGER = configure_logger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _validated_token(token: Mapping[str, Any]) -> FlumeToken:
|
|
35
|
+
"""Validate required OAuth token fields while preserving extra fields."""
|
|
36
|
+
access_token = token.get("access_token")
|
|
37
|
+
if not isinstance(access_token, str) or not access_token:
|
|
38
|
+
raise FlumeResponseError(
|
|
39
|
+
"Flume token response did not include an access token."
|
|
40
|
+
)
|
|
41
|
+
return cast(FlumeToken, cast(object, dict(token)))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class FlumeAuth: # noqa: WPS214
|
|
45
|
+
"""Interact with API Authentication."""
|
|
46
|
+
|
|
47
|
+
capabilities: ClassVar[FrozenSet[str]] = frozenset({"personal_api"})
|
|
48
|
+
|
|
49
|
+
def __init__( # noqa: WPS211
|
|
50
|
+
self,
|
|
51
|
+
username: str,
|
|
52
|
+
password: str,
|
|
53
|
+
client_id: str,
|
|
54
|
+
client_secret: str,
|
|
55
|
+
flume_token: Optional[Mapping[str, Any]] = None,
|
|
56
|
+
http_session: Optional[Session] = None,
|
|
57
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
58
|
+
) -> None:
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
Initialize the data object.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
username: Username to authenticate.
|
|
65
|
+
password: Password to authenticate.
|
|
66
|
+
client_id: API client id.
|
|
67
|
+
client_secret: API client secret.
|
|
68
|
+
flume_token: Pass flume token to variable.
|
|
69
|
+
http_session: Requests Session()
|
|
70
|
+
timeout: Requests timeout for throttling.
|
|
71
|
+
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
self._creds: Dict[str, str] = {
|
|
75
|
+
"client_id": client_id,
|
|
76
|
+
"client_secret": client_secret,
|
|
77
|
+
"username": username,
|
|
78
|
+
"password": password,
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if http_session is None:
|
|
82
|
+
self._http_session = Session()
|
|
83
|
+
else:
|
|
84
|
+
self._http_session = http_session
|
|
85
|
+
|
|
86
|
+
self._timeout: float = timeout
|
|
87
|
+
self._token: Optional[FlumeToken] = None
|
|
88
|
+
self._decoded_token: Optional[Dict[str, Any]] = None
|
|
89
|
+
self.user_id: Optional[ResourceId] = None
|
|
90
|
+
self.authorization_header: Optional[Dict[str, str]] = None
|
|
91
|
+
self.rate_limit: RateLimitState = RateLimitState(120)
|
|
92
|
+
|
|
93
|
+
self._load_token(flume_token)
|
|
94
|
+
self._verify_token()
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def token(self) -> Optional[FlumeToken]:
|
|
98
|
+
"""
|
|
99
|
+
Return authorization token for session.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Returns the current JWT token.
|
|
103
|
+
|
|
104
|
+
"""
|
|
105
|
+
return self._token
|
|
106
|
+
|
|
107
|
+
def refresh_token(self) -> None:
|
|
108
|
+
"""Refresh authorization token for session."""
|
|
109
|
+
if self._token is None or "refresh_token" not in self._token:
|
|
110
|
+
self.retrieve_token()
|
|
111
|
+
return
|
|
112
|
+
payload = {
|
|
113
|
+
"grant_type": "refresh_token",
|
|
114
|
+
"refresh_token": self._token["refresh_token"],
|
|
115
|
+
"client_id": self._creds["client_id"],
|
|
116
|
+
"client_secret": self._creds["client_secret"],
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
self._load_token(self._request_token(payload))
|
|
120
|
+
|
|
121
|
+
def refresh(self) -> None:
|
|
122
|
+
"""Refresh through the common PyFlumeNG auth interface."""
|
|
123
|
+
self.refresh_token()
|
|
124
|
+
|
|
125
|
+
def ensure_valid(self) -> None:
|
|
126
|
+
"""Refresh when the token expires within twelve hours."""
|
|
127
|
+
self._verify_token()
|
|
128
|
+
|
|
129
|
+
def retrieve_token(self) -> None:
|
|
130
|
+
"""Return authorization token for session."""
|
|
131
|
+
|
|
132
|
+
payload = dict({"grant_type": "password"}, **self._creds)
|
|
133
|
+
self._load_token(self._request_token(payload))
|
|
134
|
+
|
|
135
|
+
def _load_token(self, token: Optional[Mapping[str, Any]]) -> None:
|
|
136
|
+
"""
|
|
137
|
+
Update _token, decode token, user_id and auth header.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
token: Authentication bearer token to be decoded.
|
|
141
|
+
|
|
142
|
+
"""
|
|
143
|
+
if token is None:
|
|
144
|
+
self.retrieve_token()
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
jwt_options: Options = {"verify_signature": False}
|
|
148
|
+
self._token = _validated_token(token)
|
|
149
|
+
try:
|
|
150
|
+
self._decoded_token = jwt.decode(
|
|
151
|
+
self._token["access_token"],
|
|
152
|
+
options=jwt_options,
|
|
153
|
+
)
|
|
154
|
+
except jwt.exceptions.DecodeError:
|
|
155
|
+
LOGGER.debug("Poorly formatted Access Token, fetching token using _creds")
|
|
156
|
+
self.retrieve_token()
|
|
157
|
+
except TypeError:
|
|
158
|
+
LOGGER.debug("Token TypeError, fetching token using _creds")
|
|
159
|
+
self.retrieve_token()
|
|
160
|
+
|
|
161
|
+
if self._decoded_token is None:
|
|
162
|
+
raise FlumeResponseError("Flume token could not be decoded.")
|
|
163
|
+
self.user_id = self._decoded_token["user_id"]
|
|
164
|
+
|
|
165
|
+
self.authorization_header = {
|
|
166
|
+
"authorization": "Bearer {0}".format(self._token.get("access_token")),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
def _request_token(self, payload: Mapping[str, str]) -> FlumeToken:
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
Request Authorization Payload.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
payload: Request payload to get token request.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
Return response Authentication Bearer token from request.
|
|
179
|
+
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
headers = {"content-type": "application/json"}
|
|
183
|
+
response = self._http_session.request(
|
|
184
|
+
"POST",
|
|
185
|
+
URL_OAUTH_TOKEN,
|
|
186
|
+
json=payload,
|
|
187
|
+
headers=headers,
|
|
188
|
+
timeout=self._timeout,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
LOGGER.debug("Token Payload: %s", payload) # noqa: WPS323
|
|
192
|
+
LOGGER.debug("Token Response: %s", response.text) # noqa: WPS323
|
|
193
|
+
|
|
194
|
+
# Check for response errors.
|
|
195
|
+
flume_response_error(
|
|
196
|
+
"Can't get token for user {0}".format(self._creds.get("username")),
|
|
197
|
+
response,
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
token_data = json.loads(response.text)["data"][0]
|
|
201
|
+
if not isinstance(token_data, Mapping):
|
|
202
|
+
raise FlumeResponseError("Flume token response was not an object.")
|
|
203
|
+
return _validated_token(token_data)
|
|
204
|
+
|
|
205
|
+
def _verify_token(self) -> None:
|
|
206
|
+
"""Check to see if token is expiring in 12 hours."""
|
|
207
|
+
if self._decoded_token is None:
|
|
208
|
+
self.retrieve_token()
|
|
209
|
+
if self._decoded_token is None:
|
|
210
|
+
raise FlumeResponseError("Flume token could not be decoded.")
|
|
211
|
+
token_expiration = datetime.fromtimestamp(
|
|
212
|
+
self._decoded_token["exp"], tz=timezone.utc
|
|
213
|
+
)
|
|
214
|
+
time_difference = datetime.now(timezone.utc) + timedelta(hours=12) # noqa: WPS432
|
|
215
|
+
LOGGER.debug("Token expiration time: %s", token_expiration) # noqa: WPS323
|
|
216
|
+
LOGGER.debug("Token comparison time: %s", time_difference) # noqa: WPS323
|
|
217
|
+
|
|
218
|
+
if token_expiration <= time_difference:
|
|
219
|
+
self.refresh_token()
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class FlumePortalAuth: # noqa: WPS214
|
|
223
|
+
"""Authenticate using the customer portal OAuth authorization-code flow.
|
|
224
|
+
|
|
225
|
+
The Personal API password grant produces a token with ``update:personal``
|
|
226
|
+
scope, but usage-alert rule writes require the portal's ``customer-portal``
|
|
227
|
+
client and its broader ``update`` scope.
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
capabilities: ClassVar[FrozenSet[str]] = frozenset(
|
|
231
|
+
{"personal_api", "portal_api", "portal_writes"}
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
def __init__(
|
|
235
|
+
self,
|
|
236
|
+
username: str,
|
|
237
|
+
password: str,
|
|
238
|
+
flume_token: Optional[Mapping[str, Any]] = None,
|
|
239
|
+
http_session: Optional[Session] = None,
|
|
240
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
241
|
+
) -> None:
|
|
242
|
+
"""Initialize portal authentication."""
|
|
243
|
+
self._username: str = username
|
|
244
|
+
self._password: str = password
|
|
245
|
+
self._timeout: float = timeout
|
|
246
|
+
self._http_session: Session = http_session or Session()
|
|
247
|
+
self._token: Optional[FlumeToken] = None
|
|
248
|
+
self._decoded_token: Optional[Dict[str, Any]] = None
|
|
249
|
+
self.user_id: Optional[ResourceId] = None
|
|
250
|
+
self.authorization_header: Optional[Dict[str, str]] = None
|
|
251
|
+
self.rate_limit: RateLimitState = RateLimitState(72000)
|
|
252
|
+
|
|
253
|
+
if flume_token is None:
|
|
254
|
+
self.retrieve_token()
|
|
255
|
+
else:
|
|
256
|
+
self._load_token(flume_token)
|
|
257
|
+
self._verify_token()
|
|
258
|
+
|
|
259
|
+
@property
|
|
260
|
+
def token(self) -> Optional[FlumeToken]:
|
|
261
|
+
"""Return the current portal token response."""
|
|
262
|
+
return self._token
|
|
263
|
+
|
|
264
|
+
def retrieve_token(self) -> None:
|
|
265
|
+
"""Authenticate through the portal and exchange the authorization code."""
|
|
266
|
+
state = uuid4().hex
|
|
267
|
+
response = self._http_session.get(
|
|
268
|
+
PORTAL_API_URL + "/account/login",
|
|
269
|
+
params={
|
|
270
|
+
"client_id": PORTAL_CLIENT_ID,
|
|
271
|
+
"redirect_uri": PORTAL_REDIRECT_URI,
|
|
272
|
+
"state": state,
|
|
273
|
+
"response_type": "code",
|
|
274
|
+
},
|
|
275
|
+
timeout=self._timeout,
|
|
276
|
+
)
|
|
277
|
+
flume_response_error("Can't open portal login", response)
|
|
278
|
+
response = self._http_session.post(
|
|
279
|
+
PORTAL_OAUTH_AUTHORIZE_URL,
|
|
280
|
+
data={
|
|
281
|
+
"username": self._username,
|
|
282
|
+
"password": self._password,
|
|
283
|
+
"response_type": "code",
|
|
284
|
+
"client_id": PORTAL_CLIENT_ID,
|
|
285
|
+
"redirect_uri": PORTAL_REDIRECT_URI,
|
|
286
|
+
"state": state,
|
|
287
|
+
},
|
|
288
|
+
allow_redirects=False,
|
|
289
|
+
timeout=self._timeout,
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
if response.status_code not in (301, 302, 303, 307, 308):
|
|
293
|
+
raise FlumeResponseError(
|
|
294
|
+
"Can't authorize user {0}. Response code returned:{1}.".format(
|
|
295
|
+
self._username,
|
|
296
|
+
response.status_code,
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
location = response.headers.get("Location")
|
|
301
|
+
params = parse_qs(urlparse(location or "").query)
|
|
302
|
+
code = params.get("code", [None])[0]
|
|
303
|
+
returned_state = params.get("state", [None])[0]
|
|
304
|
+
error = params.get("error", [None])[0]
|
|
305
|
+
if error:
|
|
306
|
+
raise FlumeResponseError(
|
|
307
|
+
"Portal authorization failed: {0}".format(error),
|
|
308
|
+
)
|
|
309
|
+
if code is None or returned_state != state:
|
|
310
|
+
raise FlumeResponseError(
|
|
311
|
+
"Portal authorization did not return a valid code.",
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
self._load_token(
|
|
315
|
+
self._request_portal_token(
|
|
316
|
+
{
|
|
317
|
+
"client_id": PORTAL_CLIENT_ID,
|
|
318
|
+
"code": code,
|
|
319
|
+
"grant_type": "authorization_code",
|
|
320
|
+
"redirect_uri": PORTAL_REDIRECT_URI,
|
|
321
|
+
}
|
|
322
|
+
)
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
def refresh_token(self) -> None:
|
|
326
|
+
"""Refresh the portal token using its form-encoded refresh flow."""
|
|
327
|
+
if self._token is None or "refresh_token" not in self._token:
|
|
328
|
+
self.retrieve_token()
|
|
329
|
+
return
|
|
330
|
+
response = self._http_session.post(
|
|
331
|
+
PORTAL_OAUTH_TOKEN_URL,
|
|
332
|
+
data=(
|
|
333
|
+
"grant_type=refresh_token&client_id={0}&refresh_token={1}".format(
|
|
334
|
+
PORTAL_CLIENT_ID,
|
|
335
|
+
self._token["refresh_token"],
|
|
336
|
+
)
|
|
337
|
+
),
|
|
338
|
+
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
339
|
+
timeout=self._timeout,
|
|
340
|
+
)
|
|
341
|
+
flume_response_error("Can't refresh portal token", response)
|
|
342
|
+
self._load_token(response.json()["data"][0])
|
|
343
|
+
|
|
344
|
+
def refresh(self) -> None:
|
|
345
|
+
"""Refresh through the common PyFlumeNG auth interface."""
|
|
346
|
+
self.refresh_token()
|
|
347
|
+
|
|
348
|
+
def ensure_valid(self) -> None:
|
|
349
|
+
"""Refresh when the token expires within twelve hours."""
|
|
350
|
+
self._verify_token()
|
|
351
|
+
|
|
352
|
+
def _load_token(self, token: Mapping[str, Any]) -> None:
|
|
353
|
+
"""Update token, user ID, decoded claims, and authorization header."""
|
|
354
|
+
self._token = _validated_token(token)
|
|
355
|
+
decoded_token = jwt.decode(
|
|
356
|
+
self._token["access_token"],
|
|
357
|
+
options={"verify_signature": False},
|
|
358
|
+
)
|
|
359
|
+
self._decoded_token = decoded_token
|
|
360
|
+
self.user_id = decoded_token["user_id"]
|
|
361
|
+
self.authorization_header = {
|
|
362
|
+
"authorization": "Bearer {0}".format(self._token["access_token"]),
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
def _request_portal_token(self, payload: JSONDict) -> FlumeToken:
|
|
366
|
+
"""Exchange a portal authorization code for an access token."""
|
|
367
|
+
response = self._http_session.post(
|
|
368
|
+
PORTAL_OAUTH_TOKEN_URL,
|
|
369
|
+
json=payload,
|
|
370
|
+
headers={"Content-Type": "application/json"},
|
|
371
|
+
timeout=self._timeout,
|
|
372
|
+
)
|
|
373
|
+
flume_response_error("Can't get portal token", response)
|
|
374
|
+
token_data = response.json()["data"][0]
|
|
375
|
+
if not isinstance(token_data, Mapping):
|
|
376
|
+
raise FlumeResponseError("Flume portal token response was not an object.")
|
|
377
|
+
return _validated_token(token_data)
|
|
378
|
+
|
|
379
|
+
def _verify_token(self) -> None:
|
|
380
|
+
"""Refresh when the token expires within twelve hours."""
|
|
381
|
+
if self._decoded_token is None:
|
|
382
|
+
self.retrieve_token()
|
|
383
|
+
if self._decoded_token is None:
|
|
384
|
+
raise FlumeResponseError("Flume portal token could not be decoded.")
|
|
385
|
+
token_expiration = datetime.fromtimestamp(
|
|
386
|
+
self._decoded_token["exp"], tz=timezone.utc
|
|
387
|
+
)
|
|
388
|
+
time_difference = datetime.now(timezone.utc) + timedelta(hours=12) # noqa: WPS432
|
|
389
|
+
if token_expiration <= time_difference:
|
|
390
|
+
self.refresh_token()
|