skapi 2.4.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.
- skapi/__init__.py +15 -0
- skapi/_cognito.py +386 -0
- skapi/_database.py +1454 -0
- skapi/_encryption.py +1359 -0
- skapi/_forward.py +484 -0
- skapi/_http.py +373 -0
- skapi/_md5.py +94 -0
- skapi/_project.py +83 -0
- skapi/_realtime.py +549 -0
- skapi/_social.py +323 -0
- skapi/_srp.py +126 -0
- skapi/_user.py +880 -0
- skapi/_ws.py +176 -0
- skapi/client.py +270 -0
- skapi/errors.py +26 -0
- skapi-2.4.0.dist-info/METADATA +46 -0
- skapi-2.4.0.dist-info/RECORD +20 -0
- skapi-2.4.0.dist-info/WHEEL +5 -0
- skapi-2.4.0.dist-info/licenses/LICENSE +201 -0
- skapi-2.4.0.dist-info/top_level.txt +1 -0
skapi/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""
|
|
2
|
+
skapi: the Skapi backend for Python. Sign users in, keep their sessions, and read and write your
|
|
3
|
+
project's database with the same API as skapi-js.
|
|
4
|
+
|
|
5
|
+
from skapi import Skapi
|
|
6
|
+
skapi = Skapi("<Project ID>")
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
__version__ = "2.4.0"
|
|
10
|
+
|
|
11
|
+
from .errors import SkapiError # noqa: E402
|
|
12
|
+
from .client import Skapi # noqa: E402
|
|
13
|
+
from ._cognito import FileStorage, MemoryStorage # noqa: E402
|
|
14
|
+
|
|
15
|
+
__all__ = ["Skapi", "SkapiError", "FileStorage", "MemoryStorage", "__version__"]
|
skapi/_cognito.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The Cognito user pool client skapi-py signs in with, ported from skapi-js (src/cognito/index.ts).
|
|
3
|
+
|
|
4
|
+
Same requests, error codes and messages, retry timing and storage keys
|
|
5
|
+
(CognitoIdentityServiceProvider.<clientId>.LastAuthUser and .<username>.idToken / accessToken /
|
|
6
|
+
refreshToken / clockDrift). Sign-in is SRP only: the password never leaves the machine. No device
|
|
7
|
+
tracking (off on every Skapi user pool) and no text messages of any kind.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import hashlib
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import tempfile
|
|
19
|
+
import threading
|
|
20
|
+
import time
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.request
|
|
23
|
+
from typing import Any, Dict, Optional
|
|
24
|
+
|
|
25
|
+
from ._srp import SrpHelper, cognito_timestamp, hex_to_int
|
|
26
|
+
|
|
27
|
+
REQUEST_TIMEOUT = 60 # seconds per call to the user pool API
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class CognitoError(Exception):
|
|
31
|
+
"""An error answered by the user pool API, or a network failure (code 'NetworkError')."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, message: Optional[str], code: str, status: Optional[int] = None):
|
|
34
|
+
super().__init__(message)
|
|
35
|
+
self.message = message
|
|
36
|
+
self.code = code
|
|
37
|
+
self.name = code
|
|
38
|
+
self.status = status
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# ---- storage ------------------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
class MemoryStorage:
|
|
44
|
+
"""Kept for the life of the Skapi object only."""
|
|
45
|
+
|
|
46
|
+
def __init__(self):
|
|
47
|
+
self._data: Dict[str, str] = {}
|
|
48
|
+
|
|
49
|
+
def get_item(self, key: str) -> Optional[str]:
|
|
50
|
+
return self._data.get(key)
|
|
51
|
+
|
|
52
|
+
def set_item(self, key: str, value: str) -> None:
|
|
53
|
+
self._data[key] = value
|
|
54
|
+
|
|
55
|
+
def remove_item(self, key: str) -> None:
|
|
56
|
+
self._data.pop(key, None)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class FileStorage:
|
|
60
|
+
"""
|
|
61
|
+
One JSON file, so a script that runs again stays signed in. The file holds tokens: keep it out
|
|
62
|
+
of version control and readable by you only (it is created with mode 600).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, path: str):
|
|
66
|
+
self.path = os.path.abspath(os.path.expanduser(path))
|
|
67
|
+
self._lock = threading.Lock()
|
|
68
|
+
|
|
69
|
+
def _read(self) -> Dict[str, str]:
|
|
70
|
+
try:
|
|
71
|
+
with open(self.path, "r", encoding="utf-8") as f:
|
|
72
|
+
data = json.load(f)
|
|
73
|
+
return data if isinstance(data, dict) else {}
|
|
74
|
+
except (FileNotFoundError, ValueError):
|
|
75
|
+
return {}
|
|
76
|
+
|
|
77
|
+
def _write(self, data: Dict[str, str]) -> None:
|
|
78
|
+
directory = os.path.dirname(self.path) or "."
|
|
79
|
+
os.makedirs(directory, exist_ok=True)
|
|
80
|
+
fd, tmp = tempfile.mkstemp(dir=directory, prefix=".skapi-", suffix=".tmp")
|
|
81
|
+
try:
|
|
82
|
+
os.chmod(tmp, 0o600)
|
|
83
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
84
|
+
json.dump(data, f)
|
|
85
|
+
os.replace(tmp, self.path)
|
|
86
|
+
except BaseException:
|
|
87
|
+
try:
|
|
88
|
+
os.unlink(tmp)
|
|
89
|
+
except OSError:
|
|
90
|
+
pass
|
|
91
|
+
raise
|
|
92
|
+
|
|
93
|
+
def get_item(self, key: str) -> Optional[str]:
|
|
94
|
+
return self._read().get(key)
|
|
95
|
+
|
|
96
|
+
def set_item(self, key: str, value: str) -> None:
|
|
97
|
+
with self._lock:
|
|
98
|
+
data = self._read()
|
|
99
|
+
data[key] = value
|
|
100
|
+
self._write(data)
|
|
101
|
+
|
|
102
|
+
def remove_item(self, key: str) -> None:
|
|
103
|
+
with self._lock:
|
|
104
|
+
data = self._read()
|
|
105
|
+
if key in data:
|
|
106
|
+
del data[key]
|
|
107
|
+
self._write(data)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def make_storage(storage: Any):
|
|
111
|
+
"""None: memory. A str or os.PathLike: a JSON file. Anything else: an object with get_item/set_item/remove_item."""
|
|
112
|
+
if storage is None:
|
|
113
|
+
return MemoryStorage()
|
|
114
|
+
if isinstance(storage, (str, os.PathLike)):
|
|
115
|
+
return FileStorage(os.fspath(storage))
|
|
116
|
+
for name in ("get_item", "set_item", "remove_item"):
|
|
117
|
+
if not callable(getattr(storage, name, None)):
|
|
118
|
+
raise TypeError("storage needs get_item(key), set_item(key, value) and remove_item(key).")
|
|
119
|
+
return storage
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---- tokens and session -------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def _b64_any(text: str) -> bytes:
|
|
125
|
+
"""Base64 in the standard or URL-safe alphabet, padding optional, like Node's Buffer.from(text, 'base64')."""
|
|
126
|
+
text = text.split("=")[0].replace("-", "+").replace("_", "/")
|
|
127
|
+
text += "=" * (-len(text) % 4)
|
|
128
|
+
return base64.b64decode(text, validate=False)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class JwtToken:
|
|
132
|
+
def __init__(self, token: Optional[str] = None):
|
|
133
|
+
self.jwt_token: str = token or ""
|
|
134
|
+
self.payload: Dict[str, Any] = self._decode_payload()
|
|
135
|
+
|
|
136
|
+
def _decode_payload(self) -> Dict[str, Any]:
|
|
137
|
+
try:
|
|
138
|
+
return json.loads(_b64_any(self.jwt_token.split(".")[1]).decode("utf-8"))
|
|
139
|
+
except Exception:
|
|
140
|
+
return {}
|
|
141
|
+
|
|
142
|
+
@property
|
|
143
|
+
def expiration(self) -> int:
|
|
144
|
+
return self.payload.get("exp")
|
|
145
|
+
|
|
146
|
+
@property
|
|
147
|
+
def issued_at(self) -> int:
|
|
148
|
+
return self.payload.get("iat")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class Session:
|
|
152
|
+
def __init__(self, id_token: str, access_token: str, refresh_token: Optional[str], clock_drift: Optional[int] = None):
|
|
153
|
+
self.id_token = JwtToken(id_token)
|
|
154
|
+
self.access_token = JwtToken(access_token)
|
|
155
|
+
self.refresh_token: str = refresh_token or ""
|
|
156
|
+
self.clock_drift = self._calculate_clock_drift() if clock_drift is None else clock_drift
|
|
157
|
+
|
|
158
|
+
def _calculate_clock_drift(self) -> int:
|
|
159
|
+
"""Seconds this machine's clock is ahead of the token issuer's, measured when the tokens arrive."""
|
|
160
|
+
return int(time.time()) - min(self.access_token.issued_at, self.id_token.issued_at)
|
|
161
|
+
|
|
162
|
+
def is_valid(self) -> bool:
|
|
163
|
+
adjusted = int(time.time()) - self.clock_drift
|
|
164
|
+
return adjusted < self.access_token.expiration and adjusted < self.id_token.expiration
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
# ---- client ---------------------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
class CognitoClient:
|
|
170
|
+
def __init__(self, region: str):
|
|
171
|
+
self.endpoint = f"https://cognito-idp.{region}.amazonaws.com/"
|
|
172
|
+
|
|
173
|
+
def request(self, operation: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
174
|
+
"""One call to the user pool API. Keys whose value is None are left out, as JSON.stringify drops undefined."""
|
|
175
|
+
body = json.dumps({k: v for k, v in params.items() if v is not None}).encode("utf-8")
|
|
176
|
+
req = urllib.request.Request(self.endpoint, data=body, method="POST", headers={
|
|
177
|
+
"Content-Type": "application/x-amz-json-1.1",
|
|
178
|
+
"X-Amz-Target": f"AWSCognitoIdentityProviderService.{operation}",
|
|
179
|
+
"Cache-Control": "no-store",
|
|
180
|
+
})
|
|
181
|
+
try:
|
|
182
|
+
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
|
|
183
|
+
raw = resp.read()
|
|
184
|
+
try:
|
|
185
|
+
return json.loads(raw.decode("utf-8")) if raw else {}
|
|
186
|
+
except ValueError:
|
|
187
|
+
return {}
|
|
188
|
+
except urllib.error.HTTPError as err:
|
|
189
|
+
raw = err.read()
|
|
190
|
+
try:
|
|
191
|
+
data = json.loads(raw.decode("utf-8")) if raw else {}
|
|
192
|
+
except ValueError:
|
|
193
|
+
data = {}
|
|
194
|
+
kind = data.get("__type") or data.get("code")
|
|
195
|
+
if kind:
|
|
196
|
+
code = kind.split("#")[-1]
|
|
197
|
+
raise CognitoError(data.get("message") or data.get("Message"), code, err.code) from None
|
|
198
|
+
header = err.headers.get("x-amzn-errortype") if err.headers else None
|
|
199
|
+
if header:
|
|
200
|
+
raise CognitoError(str(err.code), header.split(":")[0], err.code) from None
|
|
201
|
+
raise CognitoError(str(err.code), "UnknownError", err.code) from None
|
|
202
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError):
|
|
203
|
+
raise CognitoError("Network error", "NetworkError") from None
|
|
204
|
+
|
|
205
|
+
def request_with_retry(self, operation: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
206
|
+
"""
|
|
207
|
+
request() with jittered exponential retries on ANY error, as skapi-js does for a token
|
|
208
|
+
refresh: waits of about 0.2, 0.4, 0.8, 1.6 and 3.2 seconds (plus up to 0.1 s), then gives
|
|
209
|
+
up when the next wait would pass 5 seconds.
|
|
210
|
+
"""
|
|
211
|
+
attempt = 1
|
|
212
|
+
while True:
|
|
213
|
+
try:
|
|
214
|
+
return self.request(operation, params)
|
|
215
|
+
except CognitoError:
|
|
216
|
+
delay = (2 ** attempt) * 100 + 100 * random.random()
|
|
217
|
+
if delay > 5000:
|
|
218
|
+
raise
|
|
219
|
+
time.sleep(delay / 1000)
|
|
220
|
+
attempt += 1
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ---- the user pool, as skapi-py uses it ---------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
class Challenge(Exception):
|
|
226
|
+
"""Raised by sign-in steps that need one more answer (new password, authenticator code)."""
|
|
227
|
+
|
|
228
|
+
def __init__(self, name: str, parameters: Dict[str, Any], session: str):
|
|
229
|
+
super().__init__(name)
|
|
230
|
+
self.name = name
|
|
231
|
+
self.parameters = parameters or {}
|
|
232
|
+
self.session = session
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class UserPool:
|
|
236
|
+
def __init__(self, user_pool_id: str, client_id: str, storage):
|
|
237
|
+
if not user_pool_id or not client_id:
|
|
238
|
+
raise ValueError("Both UserPoolId and ClientId are required.")
|
|
239
|
+
self.user_pool_id = user_pool_id
|
|
240
|
+
self.client_id = client_id
|
|
241
|
+
self.pool_name = user_pool_id.split("_")[1]
|
|
242
|
+
self.client = CognitoClient(user_pool_id.split("_")[0])
|
|
243
|
+
self.storage = storage
|
|
244
|
+
self.key_prefix = f"CognitoIdentityServiceProvider.{client_id}"
|
|
245
|
+
|
|
246
|
+
# -- storage --------------------------------------------------------------------------------
|
|
247
|
+
|
|
248
|
+
def last_auth_user(self) -> Optional[str]:
|
|
249
|
+
return self.storage.get_item(f"{self.key_prefix}.LastAuthUser")
|
|
250
|
+
|
|
251
|
+
def cache_tokens(self, username: str, session: Session) -> None:
|
|
252
|
+
p = f"{self.key_prefix}.{username}"
|
|
253
|
+
self.storage.set_item(f"{p}.idToken", session.id_token.jwt_token)
|
|
254
|
+
self.storage.set_item(f"{p}.accessToken", session.access_token.jwt_token)
|
|
255
|
+
self.storage.set_item(f"{p}.refreshToken", session.refresh_token)
|
|
256
|
+
self.storage.set_item(f"{p}.clockDrift", str(session.clock_drift))
|
|
257
|
+
self.storage.set_item(f"{self.key_prefix}.LastAuthUser", username)
|
|
258
|
+
|
|
259
|
+
def clear_cached_tokens(self, username: str) -> None:
|
|
260
|
+
p = f"{self.key_prefix}.{username}"
|
|
261
|
+
for key in (f"{p}.idToken", f"{p}.accessToken", f"{p}.refreshToken", f"{self.key_prefix}.LastAuthUser", f"{p}.clockDrift", f"{p}.userData"):
|
|
262
|
+
self.storage.remove_item(key)
|
|
263
|
+
|
|
264
|
+
def cached_session(self, username: str) -> Optional[Session]:
|
|
265
|
+
p = f"{self.key_prefix}.{username}"
|
|
266
|
+
id_token = self.storage.get_item(f"{p}.idToken")
|
|
267
|
+
if not id_token:
|
|
268
|
+
return None
|
|
269
|
+
try:
|
|
270
|
+
clock_drift = int(self.storage.get_item(f"{p}.clockDrift") or 0)
|
|
271
|
+
except ValueError:
|
|
272
|
+
clock_drift = 0
|
|
273
|
+
return Session(id_token, self.storage.get_item(f"{p}.accessToken") or "", self.storage.get_item(f"{p}.refreshToken") or "", clock_drift)
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def session_from_result(result: Dict[str, Any], refresh_token: Optional[str] = None) -> Session:
|
|
277
|
+
return Session(result.get("IdToken"), result.get("AccessToken"), result.get("RefreshToken") or refresh_token)
|
|
278
|
+
|
|
279
|
+
# -- sign-up and sign-in -------------------------------------------------------------------
|
|
280
|
+
|
|
281
|
+
def sign_up(self, username: str, password: str, attributes: list, client_metadata: Optional[dict] = None) -> Dict[str, Any]:
|
|
282
|
+
return self.client.request("SignUp", {
|
|
283
|
+
"ClientId": self.client_id,
|
|
284
|
+
"Username": username,
|
|
285
|
+
"Password": password,
|
|
286
|
+
"UserAttributes": attributes,
|
|
287
|
+
"ValidationData": None,
|
|
288
|
+
"ClientMetadata": client_metadata,
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
def authenticate(self, username: str, password: str):
|
|
292
|
+
"""
|
|
293
|
+
SRP sign-in. Returns (username_for_srp, Session) on success, or raises Challenge for a next
|
|
294
|
+
step (NEW_PASSWORD_REQUIRED, SOFTWARE_TOKEN_MFA, ...) and CognitoError for a refusal.
|
|
295
|
+
"""
|
|
296
|
+
helper = SrpHelper(self.pool_name)
|
|
297
|
+
data = self.client.request("InitiateAuth", {
|
|
298
|
+
"AuthFlow": "USER_SRP_AUTH",
|
|
299
|
+
"ClientId": self.client_id,
|
|
300
|
+
"AuthParameters": {"USERNAME": username, "SRP_A": format(helper.large_a, "x")},
|
|
301
|
+
"ClientMetadata": {},
|
|
302
|
+
})
|
|
303
|
+
params = data["ChallengeParameters"]
|
|
304
|
+
srp_username = params["USER_ID_FOR_SRP"]
|
|
305
|
+
hkdf = helper.get_password_authentication_key(srp_username, password, hex_to_int(params["SRP_B"]), hex_to_int(params["SALT"]))
|
|
306
|
+
now = cognito_timestamp()
|
|
307
|
+
message = self.pool_name.encode("utf-8") + srp_username.encode("utf-8") + _b64_any(params["SECRET_BLOCK"]) + now.encode("utf-8")
|
|
308
|
+
signature = base64.b64encode(hmac.new(hkdf, message, hashlib.sha256).digest()).decode("ascii")
|
|
309
|
+
answer = self.client.request("RespondToAuthChallenge", {
|
|
310
|
+
"ChallengeName": "PASSWORD_VERIFIER",
|
|
311
|
+
"ClientId": self.client_id,
|
|
312
|
+
"ChallengeResponses": {
|
|
313
|
+
"USERNAME": srp_username,
|
|
314
|
+
"PASSWORD_CLAIM_SECRET_BLOCK": params["SECRET_BLOCK"],
|
|
315
|
+
"TIMESTAMP": now,
|
|
316
|
+
"PASSWORD_CLAIM_SIGNATURE": signature,
|
|
317
|
+
},
|
|
318
|
+
"Session": data.get("Session"),
|
|
319
|
+
"ClientMetadata": {},
|
|
320
|
+
})
|
|
321
|
+
return srp_username, self._finish(srp_username, answer)
|
|
322
|
+
|
|
323
|
+
def _finish(self, username: str, answer: Dict[str, Any]) -> Session:
|
|
324
|
+
name = answer.get("ChallengeName")
|
|
325
|
+
if name == "DEVICE_SRP_AUTH":
|
|
326
|
+
raise CognitoError("Device authentication is not supported.", "DeviceAuthenticationNotSupported")
|
|
327
|
+
if name:
|
|
328
|
+
raise Challenge(name, answer.get("ChallengeParameters"), answer.get("Session"))
|
|
329
|
+
session = self.session_from_result(answer["AuthenticationResult"])
|
|
330
|
+
self.cache_tokens(username, session)
|
|
331
|
+
return session
|
|
332
|
+
|
|
333
|
+
def complete_new_password(self, username: str, new_password: str, challenge_session: str) -> Session:
|
|
334
|
+
answer = self.client.request("RespondToAuthChallenge", {
|
|
335
|
+
"ChallengeName": "NEW_PASSWORD_REQUIRED",
|
|
336
|
+
"ClientId": self.client_id,
|
|
337
|
+
"ChallengeResponses": {"NEW_PASSWORD": new_password, "USERNAME": username},
|
|
338
|
+
"Session": challenge_session,
|
|
339
|
+
})
|
|
340
|
+
return self._finish(username, answer)
|
|
341
|
+
|
|
342
|
+
def send_mfa_code(self, username: str, code: str, challenge_session: str) -> Session:
|
|
343
|
+
answer = self.client.request("RespondToAuthChallenge", {
|
|
344
|
+
"ChallengeName": "SOFTWARE_TOKEN_MFA",
|
|
345
|
+
"ChallengeResponses": {"USERNAME": username, "SMS_MFA_CODE": code, "SOFTWARE_TOKEN_MFA_CODE": code},
|
|
346
|
+
"ClientId": self.client_id,
|
|
347
|
+
"Session": challenge_session,
|
|
348
|
+
})
|
|
349
|
+
return self._finish(username, answer)
|
|
350
|
+
|
|
351
|
+
def select_mfa_type(self, username: str, answer_name: str, challenge_session: str) -> Challenge:
|
|
352
|
+
data = self.client.request("RespondToAuthChallenge", {
|
|
353
|
+
"ChallengeName": "SELECT_MFA_TYPE",
|
|
354
|
+
"ChallengeResponses": {"USERNAME": username, "ANSWER": answer_name},
|
|
355
|
+
"ClientId": self.client_id,
|
|
356
|
+
"Session": challenge_session,
|
|
357
|
+
})
|
|
358
|
+
return Challenge(data.get("ChallengeName") or answer_name, data.get("ChallengeParameters"), data.get("Session"))
|
|
359
|
+
|
|
360
|
+
# -- session --------------------------------------------------------------------------------
|
|
361
|
+
|
|
362
|
+
def refresh(self, username: str, refresh_token: str) -> Session:
|
|
363
|
+
"""REFRESH_TOKEN_AUTH with retries. A NotAuthorizedException ends the stored session."""
|
|
364
|
+
auth = {"REFRESH_TOKEN": refresh_token}
|
|
365
|
+
if self.last_auth_user():
|
|
366
|
+
username = self.last_auth_user()
|
|
367
|
+
# sent as skapi-js sends it: null, since no device is ever remembered
|
|
368
|
+
auth["DEVICE_KEY"] = self.storage.get_item(f"{self.key_prefix}.{username}.deviceKey")
|
|
369
|
+
params = {"ClientId": self.client_id, "AuthFlow": "REFRESH_TOKEN_AUTH", "AuthParameters": auth}
|
|
370
|
+
try:
|
|
371
|
+
result = self.client.request_with_retry("InitiateAuth", params)
|
|
372
|
+
except CognitoError as err:
|
|
373
|
+
if err.code == "NotAuthorizedException":
|
|
374
|
+
self.clear_cached_tokens(username)
|
|
375
|
+
raise
|
|
376
|
+
session = self.session_from_result(result["AuthenticationResult"], refresh_token)
|
|
377
|
+
self.cache_tokens(username, session)
|
|
378
|
+
return session
|
|
379
|
+
|
|
380
|
+
# -- calls made with the access token -----------------------------------------------------
|
|
381
|
+
|
|
382
|
+
def call(self, operation: str, access_token: str, **params) -> Dict[str, Any]:
|
|
383
|
+
return self.client.request(operation, dict(params, AccessToken=access_token))
|
|
384
|
+
|
|
385
|
+
def call_public(self, operation: str, **params) -> Dict[str, Any]:
|
|
386
|
+
return self.client.request(operation, dict(params, ClientId=self.client_id))
|