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/_user.py ADDED
@@ -0,0 +1,880 @@
1
+ """
2
+ Account methods, ported from skapi-js (src/methods/user.ts): sign-up, sign-in (with authenticator app
3
+ MFA), sessions, profile, password and e-mail verification, and user search.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import re
10
+ import threading
11
+ from typing import Any, Dict, Optional
12
+ from urllib.parse import quote, urlsplit
13
+
14
+ from ._cognito import Challenge, CognitoError, JwtToken, Session
15
+ from ._md5 import md5_js
16
+ from .errors import SkapiError
17
+
18
+ _SKIP_CLAIMS = {"aud", "cognito:username", "event_id", "exp", "iat", "iss", "jti", "origin_jti", "secret_key", "token_use"}
19
+ _RENAME_CLAIMS = {"auth_time": "log", "sub": "user_id"}
20
+ _EMAIL = re.compile(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$")
21
+ _BIRTHDATE = re.compile(r"([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))")
22
+ _UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)
23
+ ANONYMOUS_KEEPALIVE_SECONDS = 600
24
+ PROFILE_KEYS = ["email", "name", "address", "gender", "birthdate", "phone_number", "email_public", "address_public",
25
+ "gender_public", "birthdate_public", "phone_number_public", "misc", "picture", "profile", "family_name",
26
+ "given_name", "middle_name", "nickname", "website"]
27
+ _CUSTOM = {"email_public", "address_public", "gender_public", "birthdate_public", "phone_number_public", "misc", "service", "owner"}
28
+
29
+
30
+ def _jd(v):
31
+ """A value as it appears in an error message; never fails on odd types."""
32
+ return json.dumps(v, default=repr, ensure_ascii=False)
33
+
34
+
35
+ def _p(message: str, code: str = "INVALID_PARAMETER") -> SkapiError:
36
+ return SkapiError(message, code)
37
+
38
+
39
+ def parse_user_attributes(claims: Dict[str, Any]) -> Dict[str, Any]:
40
+ """The ID token's claims as the user profile skapi-js returns."""
41
+ user: Dict[str, Any] = {}
42
+ username = claims.get("cognito:username")
43
+ if isinstance(username, str):
44
+ parts = username.split("-")
45
+ if len(parts) == 2 and parts[1].startswith("anon"):
46
+ user["anonymous"] = True
47
+ for k, v in claims.items():
48
+ if k in _SKIP_CLAIMS:
49
+ continue
50
+ if k in _RENAME_CLAIMS:
51
+ user[_RENAME_CLAIMS[k]] = v
52
+ elif "custom:" in k:
53
+ user[k.replace("custom:", "")] = v
54
+ elif k == "address":
55
+ if isinstance(v, dict):
56
+ if v.get("formatted"):
57
+ try:
58
+ user["address"] = json.loads(v["formatted"])
59
+ except (ValueError, TypeError):
60
+ user["address"] = v["formatted"]
61
+ else:
62
+ user["address"] = v
63
+ else:
64
+ user[k] = v
65
+ for k in ("address_public", "birthdate_public", "email_public", "gender_public", "phone_number_public"):
66
+ base = k[:-len("_public")] # the attribute the flag belongs to: "phone_number" for "phone_number_public"
67
+ if base in user:
68
+ try:
69
+ user[k] = bool(float(user.get(k) or 0))
70
+ except (TypeError, ValueError):
71
+ user[k] = False
72
+ else:
73
+ user.pop(k, None)
74
+ try:
75
+ user["access_group"] = int(float(user.get("access_group") or 0))
76
+ except (TypeError, ValueError):
77
+ user["access_group"] = 0
78
+ for k in ("email", "phone_number"):
79
+ if k in user:
80
+ user[f"{k}_verified"] = user.get(f"{k}_verified") is True
81
+ else:
82
+ user.pop(f"{k}_verified", None)
83
+ return user
84
+
85
+
86
+ def validate_email(v: Any) -> str:
87
+ if not v:
88
+ raise _p('"email" is required.')
89
+ if not isinstance(v, str):
90
+ raise _p('"email" should be type: string.')
91
+ if len(v) < 5:
92
+ raise _p('"email" should be at least 5 characters.')
93
+ if not _EMAIL.match(v) or len(v.strip().split("@")[1].split(".")) < 2:
94
+ raise _p(f'"{v}" is an invalid email.')
95
+ return v.strip().lower()
96
+
97
+
98
+ def validate_password(v: Any, field: str = "password") -> str:
99
+ if not v:
100
+ raise _p(f'"{field}" is required.')
101
+ if not isinstance(v, str):
102
+ raise _p(f'"{field}" should be type: string.')
103
+ if len(v) < 6:
104
+ raise _p(f'"{field}" should be at least 6 characters.')
105
+ if len(v) > 60:
106
+ raise _p(f'"{field}" can be up to 60 characters max.')
107
+ return v
108
+
109
+
110
+ def _phone(v):
111
+ if not v:
112
+ return ""
113
+ if not isinstance(v, str) or not v.startswith("+") or not v[1:].strip().replace(".", "", 1).isdigit():
114
+ raise _p('"phone_number" is invalid. The format should be "+00123456789". Type: string.')
115
+ return v
116
+
117
+
118
+ def _birthdate(v):
119
+ if not v:
120
+ return ""
121
+ if not isinstance(v, str) or len(v) != 10 or len(v.split("-")) != 3 or not _BIRTHDATE.search(v):
122
+ raise _p('"birthdate" is invalid. The format should be "yyyy-mm-dd". Type: string.')
123
+ return v
124
+
125
+
126
+ def _url(v):
127
+ if not v:
128
+ return ""
129
+ if v == "*":
130
+ return v
131
+ try:
132
+ parts = urlsplit(v)
133
+ if not parts.scheme or not parts.netloc:
134
+ raise ValueError
135
+ except (ValueError, TypeError):
136
+ raise _p(f'"{v}" is an invalid url.') from None
137
+ return v if parts.path else v + "/"
138
+
139
+
140
+ def _address(v):
141
+ if not v:
142
+ return ""
143
+ if isinstance(v, str):
144
+ return v
145
+ if isinstance(v, dict):
146
+ return json.dumps(v, separators=(",", ":"), ensure_ascii=False)
147
+ raise _p('"address" should be type: <string | dict>.')
148
+
149
+
150
+ def _string(field):
151
+ def check(v):
152
+ if not isinstance(v, str):
153
+ raise _p(f'{_jd(v)} is invalid in "{field}". allowed type or value is: Type<string>.')
154
+ return v
155
+ return check
156
+
157
+
158
+ def _boolean(field):
159
+ def check(v):
160
+ if not isinstance(v, bool):
161
+ raise _p(f'{_jd(v)} is invalid in "{field}". allowed type or value is: Type<boolean>.')
162
+ return v
163
+ return check
164
+
165
+
166
+ def _mfa_code(v) -> str:
167
+ code = re.sub(r"\s+", "", str(v if v is not None else ""))
168
+ if not re.match(r"^\d{6}$", code):
169
+ raise _p('"code" should be the 6 digit code from the authenticator app.')
170
+ return code
171
+
172
+
173
+ def _parsed_cognito_error(err: Any) -> SkapiError:
174
+ """'#CODE: text' messages from the pool's triggers carry their own code."""
175
+ code = (getattr(err, "code", None) or "ERROR").strip() if isinstance(getattr(err, "code", None), str) else "ERROR"
176
+ message = (getattr(err, "message", None) or str(err) or "An error occurred.").strip() or "An error occurred."
177
+ m = re.search(r"#([A-Za-z0-9_]+)\s*:\s*([\s\S]+)", message)
178
+ if m:
179
+ return SkapiError(m.group(2).strip(), m.group(1).strip(), err)
180
+ return SkapiError(message, code, err)
181
+
182
+
183
+ class UserMixin:
184
+ """Mixed into Skapi."""
185
+
186
+ # ---- helpers ----------------------------------------------------------------------------------
187
+
188
+ def _cognito_name(self, name: str) -> str:
189
+ return name if (self.service + "-") in name else f"{self.service}-{md5_js(name)}"
190
+
191
+ def _refuse_anonymous(self, what: str) -> None:
192
+ if self._user and self._user.get("anonymous"):
193
+ raise SkapiError(f"Anonymous accounts cannot {what}.", "INVALID_REQUEST")
194
+
195
+ def _require_session(self) -> None:
196
+ self._ensure_connection()
197
+ if not self._signed_in():
198
+ raise SkapiError("User login is required.", "INVALID_REQUEST")
199
+
200
+ # ---- sign-in ------------------------------------------------------------------------------
201
+
202
+ def _authenticate(self, name: str, password: str, raw: bool = False, is_openid: bool = False) -> Dict[str, Any]:
203
+ self._request_signup_confirmation = None
204
+ self._disabled_account = None
205
+ self._pending_mfa = None
206
+ pool = self._user_pool()
207
+ username = name if raw else self._cognito_name(name)
208
+ try:
209
+ srp_username, session = pool.authenticate(username, password)
210
+ self._adopt_session(srp_username, session)
211
+ self._disabled_account = None
212
+ self._enc_after_login(password)
213
+ return self.user
214
+ except Challenge as ch:
215
+ return self._handle_challenge(ch, username, password)
216
+ except CognitoError as err:
217
+ code, message = err.code, err.message or ""
218
+ if code == "NotAuthorizedException":
219
+ if "User is disabled." in message:
220
+ self._disabled_account = username
221
+ raise SkapiError("This account is disabled.", "USER_IS_DISABLED", err) from None
222
+ if is_openid:
223
+ raise SkapiError("The account already exists.", "ACCOUNT_EXISTS", err) from None
224
+ raise SkapiError("Incorrect username or password.", "INCORRECT_USERNAME_OR_PASSWORD", err) from None
225
+ if code == "UserNotFoundException":
226
+ raise SkapiError("Incorrect username or password.", "INCORRECT_USERNAME_OR_PASSWORD", err) from None
227
+ if code == "UserNotConfirmedException":
228
+ self._request_signup_confirmation = username
229
+ raise SkapiError("User's signup confirmation is required.", "SIGNUP_CONFIRMATION_NEEDED", err) from None
230
+ if code in ("TooManyRequestsException", "LimitExceededException"):
231
+ raise SkapiError("Too many attempts. Please try again later.", "REQUEST_EXCEED", err) from None
232
+ if code == "NetworkError":
233
+ raise SkapiError("Network error", "NETWORK_ERROR", err) from None
234
+ parsed = _parsed_cognito_error(err)
235
+ if parsed.code == "SIGNUP_CONFIRMATION_NEEDED":
236
+ self._request_signup_confirmation = username
237
+ raise parsed from None
238
+
239
+ def _handle_challenge(self, ch: Challenge, username: str, password: str) -> Dict[str, Any]:
240
+ pool = self._user_pool()
241
+ srp_username = ch.parameters.get("USER_ID_FOR_SRP") or username
242
+ if ch.name == "NEW_PASSWORD_REQUIRED":
243
+ self._disabled_account = None
244
+ self._request_signup_confirmation = username
245
+ attrs = {}
246
+ try:
247
+ attrs = json.loads(ch.parameters.get("userAttributes") or "{}")
248
+ except ValueError:
249
+ pass
250
+ if attrs.get("custom:signup_ticket") in ("PASS", "MEMBER", "OIDPASS"):
251
+ # an account an admin created, an invitation, or an OpenID account: confirmed by
252
+ # setting the same password
253
+ try:
254
+ session = pool.complete_new_password(srp_username, password, ch.session)
255
+ except Challenge as nxt:
256
+ return self._handle_challenge(nxt, username, password)
257
+ except CognitoError as err:
258
+ raise SkapiError(err.message or "Failed to authenticate user.", err.code, err) from None
259
+ self._adopt_session(srp_username, session)
260
+ self._enc_after_login(password)
261
+ return self.user
262
+ raise SkapiError("User's signup confirmation is required.", "SIGNUP_CONFIRMATION_NEEDED")
263
+ if ch.name == "SOFTWARE_TOKEN_MFA":
264
+ # the password stays in memory only until verify_mfa, to open the encryption keyring
265
+ self._pending_mfa = {"username": srp_username, "session": ch.session, "password": password}
266
+ raise SkapiError("A code from the authenticator app is required to sign in. Call verify_mfa() with the code.", "MFA_REQUIRED")
267
+ if ch.name == "SELECT_MFA_TYPE":
268
+ nxt = pool.select_mfa_type(srp_username, "SOFTWARE_TOKEN_MFA", ch.session)
269
+ return self._handle_challenge(nxt, username, password)
270
+ if ch.name == "SMS_MFA":
271
+ raise SkapiError("Sign-in codes by SMS are not supported.", "INVALID_REQUEST")
272
+ if ch.name == "MFA_SETUP":
273
+ raise SkapiError("The account must set up an authenticator app before signing in.", "INVALID_REQUEST")
274
+ raise SkapiError(f"Unsupported sign-in step: {ch.name}.", "INVALID_REQUEST")
275
+
276
+ def login(self, email: Optional[str] = None, password: Optional[str] = None, *, username: Optional[str] = None) -> Dict[str, Any]:
277
+ """
278
+ Signs in with the e-mail (or username) and password. Returns the user's profile.
279
+ Raises SkapiError code 'MFA_REQUIRED' when the account has two-step login on: call verify_mfa(code).
280
+ """
281
+ if not isinstance(password, str):
282
+ raise _p('Key "password" is required.' if password is None else '"password" should be type: string.')
283
+ self._user_pool()
284
+ normalized = None
285
+ if email:
286
+ try:
287
+ normalized = validate_email(email)
288
+ except SkapiError:
289
+ username = email
290
+ email = None
291
+ if not username and not email:
292
+ raise _p('At least one of "username" or "email" is required.')
293
+ typed = username or email
294
+ first = normalized or typed
295
+ fallback = typed if normalized and normalized != typed else None
296
+ try:
297
+ return self._authenticate(first, password)
298
+ except SkapiError as err:
299
+ retryable = err.code in ("INCORRECT_USERNAME_OR_PASSWORD", "UserNotFoundException", "NotAuthorizedException")
300
+ if retryable and fallback:
301
+ try:
302
+ return self._authenticate(fallback, password)
303
+ except SkapiError as second:
304
+ if second.code in ("INCORRECT_USERNAME_OR_PASSWORD", "NOT_EXISTS", "UserNotFoundException", "NotAuthorizedException"):
305
+ raise err from None
306
+ raise
307
+ raise
308
+
309
+ def verify_mfa(self, code: str) -> Dict[str, Any]:
310
+ """Finishes a login that raised MFA_REQUIRED, with the 6 digit code from the authenticator app (within 3 minutes)."""
311
+ code = _mfa_code(code)
312
+ pending = self._pending_mfa
313
+ if not pending:
314
+ raise SkapiError("No sign-in is waiting for an authenticator code. Call login() first.", "INVALID_REQUEST")
315
+ try:
316
+ session = self._user_pool().send_mfa_code(pending["username"], code, pending["session"])
317
+ except CognitoError as err:
318
+ if err.code in ("CodeMismatchException",):
319
+ raise SkapiError("Incorrect authenticator code.", "INVALID_CODE", err) from None
320
+ if err.code == "ExpiredCodeException":
321
+ raise SkapiError("This authenticator code was already used. Wait for the next code.", "INVALID_CODE", err) from None
322
+ self._pending_mfa = None
323
+ if err.code in ("TooManyRequestsException", "LimitExceededException", "TooManyFailedAttemptsException"):
324
+ raise SkapiError("Too many attempts. Please try again later.", "REQUEST_EXCEED", err) from None
325
+ if err.code == "NotAuthorizedException":
326
+ raise SkapiError("The sign-in has expired. Call login() again.", "INVALID_REQUEST", err) from None
327
+ raise _parsed_cognito_error(err) from None
328
+ self._pending_mfa = None
329
+ self._adopt_session(pending["username"], session)
330
+ self._disabled_account = None
331
+ self._enc_after_login(pending.get("password"))
332
+ return self.user
333
+
334
+ def logout(self, global_logout: bool = False) -> str:
335
+ """Signs out. global_logout=True also ends every session of the account on every device."""
336
+ self._restore()
337
+ if self._user and self._user.get("anonymous"):
338
+ try:
339
+ self._call("anonymous-session", {"end": True}, auth=True)
340
+ except SkapiError:
341
+ pass
342
+ self._clear_session()
343
+ elif global_logout and self._session:
344
+ try:
345
+ self._user_pool().call("GlobalSignOut", self._access_token())
346
+ except CognitoError as err:
347
+ raise _parsed_cognito_error(err) from None
348
+ self._clear_session()
349
+ else:
350
+ self._clear_session()
351
+ return "SUCCESS: The user has been logged out."
352
+
353
+ def get_profile(self, refresh_token: bool = False) -> Optional[Dict[str, Any]]:
354
+ """The signed-in user's profile, or None. refresh_token=True asks the server for fresh tokens first."""
355
+ if not refresh_token:
356
+ return self.user
357
+ try:
358
+ self._restore()
359
+ if self._session and self._restore_refreshed_token == self._session.id_token.jwt_token:
360
+ # the stored tokens had expired and were just refreshed: one refresh, not two
361
+ self._restore_refreshed_token = None
362
+ else:
363
+ self._refresh_session()
364
+ return self.user
365
+ except SkapiError:
366
+ return None
367
+
368
+ def login_with_token(self, id_token: str, access_token: str, refresh_token: str) -> Dict[str, Any]:
369
+ """
370
+ Adopts the tokens of a sign-in made elsewhere (for example skapi-js on a web page that sent
371
+ skapi.session's tokens to your server). All three tokens are needed to make signed-in calls.
372
+ """
373
+ for name, value in (("id_token", id_token), ("access_token", access_token), ("refresh_token", refresh_token)):
374
+ if not isinstance(value, str) or not value:
375
+ raise _p(f'"{name}" is required.')
376
+ payload = JwtToken(id_token).payload
377
+ if payload.get("custom:service") != self.service:
378
+ raise SkapiError("Token does not belong to this service.", "INVALID_REQUEST")
379
+ import time as _t
380
+ if (payload.get("exp") or 0) < _t.time():
381
+ raise SkapiError("Token has expired.", "INVALID_REQUEST")
382
+ self._restore()
383
+ session = Session(id_token, access_token, refresh_token)
384
+ username = payload.get("cognito:username")
385
+ self._adopt_session(username, session)
386
+ self._user_pool().cache_tokens(username, session)
387
+ return self.user
388
+
389
+ # ---- sign-up --------------------------------------------------------------------------------
390
+
391
+ def signup(self, params: Dict[str, Any], option: Optional[Dict[str, Any]] = None):
392
+ """
393
+ Creates an account. params: email and password (required), and any profile fields.
394
+ option: signup_confirmation (True or a redirect URL), email_subscription, login (sign in right after).
395
+ """
396
+ self._user_pool()
397
+ params = dict(params or {})
398
+ option = dict(option or {})
399
+ if "email" not in params:
400
+ raise _p('Key "email" is required.')
401
+ if "password" not in params:
402
+ raise _p('Key "password" is required.')
403
+ p: Dict[str, Any] = {}
404
+ checks = {
405
+ "username": _string("username"), "password": validate_password, "email": validate_email, "name": _string("name"),
406
+ "address": _address, "gender": _string("gender"), "birthdate": _birthdate, "phone_number": _phone,
407
+ "misc": _string("misc"), "picture": _url, "profile": _url, "family_name": _string("family_name"),
408
+ "given_name": _string("given_name"), "middle_name": _string("middle_name"), "nickname": _string("nickname"), "website": _url,
409
+ }
410
+ for k, fn in checks.items():
411
+ if k in params:
412
+ p[k] = fn(params[k])
413
+ for k in ("email_public", "address_public", "gender_public", "birthdate_public", "phone_number_public"):
414
+ p[k] = params[k] if isinstance(params.get(k), bool) else False
415
+
416
+ self.logout()
417
+
418
+ sc = option.get("signup_confirmation", False)
419
+ if isinstance(sc, str):
420
+ sc = _url(sc)
421
+ elif not isinstance(sc, bool):
422
+ raise _p('"option.signup_confirmation" should be type: <string | boolean>.')
423
+ if sc and not p.get("email"):
424
+ raise _p('"email" is required for signup confirmation.')
425
+ es = option.get("email_subscription", False)
426
+ if not isinstance(es, (bool, str, int)) or (isinstance(es, int) and not isinstance(es, bool) and es not in (0, 1)):
427
+ raise _p('"option.email_subscription" takes 0 (public), 1 (authorized), true, false or the name of a newsletter group.')
428
+ if es is not False and not sc:
429
+ raise _p('"option.signup_confirmation" is required for email subscription.')
430
+ login_after = option.get("login", False)
431
+ if not isinstance(login_after, bool):
432
+ raise _p('"option.login" should be type: boolean.')
433
+ if login_after and sc:
434
+ raise _p('"login" is not allowed when "option.signup_confirmation" is true.')
435
+ template = option.get("template") or {}
436
+ if not isinstance(template, dict):
437
+ raise _p('"option.template" should be type: <object>.')
438
+ for key in ("signup_confirmation", "welcome"):
439
+ if key in template and (not isinstance(template[key], str) or not template[key]):
440
+ raise _p(f'"option.template.{key}" should be a non-empty <string> (template message_id).')
441
+ if template.get("signup_confirmation") and not sc:
442
+ raise _p('"option.signup_confirmation" is required when "option.template.signup_confirmation" is set.')
443
+ if p.get("email_public") and not sc:
444
+ raise _p('"option.signup_confirmation" should be true if "email_public" is set to true.')
445
+
446
+ cognito_username = self._cognito_name(p.get("username") or p["email"])
447
+ key_reply = self._call("signupkey", {
448
+ "username": cognito_username,
449
+ "signup_confirmation": json.dumps(sc) if isinstance(sc, bool) else sc,
450
+ "email_subscription": es,
451
+ "template_confirmation": template.get("signup_confirmation") or "",
452
+ "template_welcome": template.get("welcome") or "",
453
+ })
454
+ parts = str(key_reply).split(":")
455
+ signup_key, signup_ticket = parts[0], ":".join(parts[1:])
456
+ attributes = [
457
+ {"Name": "custom:signup", "Value": signup_key},
458
+ {"Name": "locale", "Value": signup_ticket.split("#")[1] if "#" in signup_ticket else ""},
459
+ {"Name": "custom:signup_ticket", "Value": signup_ticket},
460
+ ]
461
+ values = dict(p, service=self.service, owner=self.owner)
462
+ for k in ["email", "name", "address", "gender", "birthdate", "phone_number", "email_public", "address_public", "gender_public",
463
+ "birthdate_public", "phone_number_public", "misc", "picture", "profile", "family_name", "given_name", "middle_name",
464
+ "nickname", "website", "service", "owner"]:
465
+ v = values.get(k)
466
+ if v == "":
467
+ continue
468
+ if k.endswith("_public"):
469
+ v = "1" if v else "0"
470
+ attributes.append({"Name": f"custom:{k}" if k in _CUSTOM else k, "Value": "" if v is None else str(v)})
471
+ try:
472
+ self._user_pool().sign_up(cognito_username, p["password"], attributes)
473
+ except CognitoError as err:
474
+ parsed = _parsed_cognito_error(err)
475
+ if err.code == "UsernameExistsException":
476
+ raise SkapiError("The account already exists.", "EXISTS", err) from None
477
+ if err.code == "InvalidPasswordException":
478
+ raise SkapiError("Invalid password. Password must be at least 6 characters.", "INVALID_PARAMETER", err) from None
479
+ if err.code == "InvalidParameterException":
480
+ raise SkapiError(parsed.message or "Invalid parameter.", "INVALID_PARAMETER", err) from None
481
+ if err.code in ("TooManyRequestsException", "LimitExceededException"):
482
+ raise SkapiError("Too many attempts. Please try again later.", "REQUEST_EXCEED", err) from None
483
+ if err.code == "CodeDeliveryFailureException":
484
+ raise SkapiError("Failed to deliver verification code.", "CODE_DELIVERY_FAILURE", err) from None
485
+ if err.code == "UserLambdaValidationException":
486
+ raise SkapiError(parsed.message or "Signup validation failed.", "EXISTS" if parsed.code == "EXISTS" else "INVALID_REQUEST", err) from None
487
+ raise parsed from None
488
+ if sc:
489
+ self._request_signup_confirmation = cognito_username
490
+ return "SUCCESS: The account has been created. User's signup confirmation is required."
491
+ if login_after:
492
+ return self.login(p.get("username") or p["email"], p["password"])
493
+ return "SUCCESS: The account has been created."
494
+
495
+ def resend_signup_confirmation(self) -> str:
496
+ if not self._request_signup_confirmation:
497
+ raise SkapiError("Least one login attempt is required.", "INVALID_REQUEST")
498
+ return self._call("confirm-signup", {"username": self._request_signup_confirmation})
499
+
500
+ def recover_account(self, redirect: Any = False) -> str:
501
+ """Sends the recovery e-mail to a disabled account, after a login attempt answered USER_IS_DISABLED."""
502
+ if isinstance(redirect, str):
503
+ redirect = _url(redirect)
504
+ elif not isinstance(redirect, bool):
505
+ raise SkapiError("Argument should be type: <boolean | string>.", "INVALID_REQUEST")
506
+ if not self._disabled_account:
507
+ raise SkapiError("Least one signin attempt of disabled account is required.", "INVALID_REQUEST")
508
+ self._call("recover-account", {"username": self._disabled_account, "redirect": redirect})
509
+ return "SUCCESS: Recovery e-mail has been sent."
510
+
511
+ def disable_account(self) -> str:
512
+ self._require_session()
513
+ self._refuse_anonymous("be disabled")
514
+ result = self._call("remove-account", {"disable": self._user["user_id"]}, auth=True)
515
+ self.logout()
516
+ return result
517
+
518
+ # ---- profile and password ---------------------------------------------------------------------
519
+
520
+ def update_profile(self, params: Dict[str, Any]) -> Dict[str, Any]:
521
+ """Changes the signed-in user's own profile fields. '' clears a field."""
522
+ self._require_session()
523
+ self._refuse_anonymous("edit their profile")
524
+ params = dict(params or {})
525
+ p: Dict[str, Any] = {}
526
+ checks = {
527
+ "email": validate_email, "address": _address, "name": _string("name"), "gender": _string("gender"),
528
+ "birthdate": _birthdate, "phone_number": _phone, "misc": _string("misc"), "picture": _url, "profile": _url,
529
+ "website": _url, "family_name": _string("family_name"), "given_name": _string("given_name"),
530
+ "middle_name": _string("middle_name"), "nickname": _string("nickname"),
531
+ }
532
+ for k in ("email_public", "phone_number_public", "address_public", "gender_public", "birthdate_public"):
533
+ checks[k] = _boolean(k)
534
+ for k, fn in checks.items():
535
+ if k in params:
536
+ p[k] = fn(params[k])
537
+ if not p:
538
+ return self.user
539
+ if p.get("email_public") and not self._user.get("email_verified"):
540
+ raise SkapiError('User\'s e-mail should be verified to set "email_public" to true.', "INVALID_REQUEST")
541
+ current = self._user or {}
542
+ attributes = []
543
+ for k, v in p.items():
544
+ if not isinstance(v, (dict, list)) and k in current and current[k] == v:
545
+ continue
546
+ name = f"custom:{k}" if k in _CUSTOM else k
547
+ if isinstance(v, bool):
548
+ v = "1" if v else "0"
549
+ attributes.append({"Name": name, "Value": "" if v is None else str(v)})
550
+ if attributes:
551
+ try:
552
+ self._user_pool().call("UpdateUserAttributes", self._access_token(), UserAttributes=attributes)
553
+ except CognitoError as err:
554
+ raise SkapiError(err.message or "Failed to update user settings.", err.code or err.name, err) from None
555
+ self._refresh_session()
556
+ return self.user
557
+
558
+ def change_password(self, current_password: str, new_password: str) -> str:
559
+ self._require_session()
560
+ self._refuse_anonymous("change their password")
561
+ if not current_password:
562
+ raise _p('"current_password" is required to change password.')
563
+ if not new_password:
564
+ raise _p('"new_password" is required to change password.')
565
+ validate_password(current_password, "current_password")
566
+ validate_password(new_password, "new_password")
567
+ # the keyring gets a wrap under the new password BEFORE the password changes (fails while locked)
568
+ rewrapped = self._enc_rewrap_password(current_password, new_password)
569
+ try:
570
+ self._user_pool().call("ChangePassword", self._access_token(), PreviousPassword=current_password, ProposedPassword=new_password)
571
+ except CognitoError as err:
572
+ if err.code == "InvalidParameterException":
573
+ raise SkapiError("Invalid password parameter.", "INVALID_PARAMETER", err) from None
574
+ if err.code == "NotAuthorizedException":
575
+ raise SkapiError("Incorrect password.", "INVALID_REQUEST", err) from None
576
+ if err.code in ("TooManyRequestsException", "LimitExceededException"):
577
+ raise SkapiError("Too many attempts. Please try again later.", "REQUEST_EXCEED", err) from None
578
+ raise _parsed_cognito_error(err) from None
579
+ if rewrapped is not None:
580
+ self._enc_prune_wraps()
581
+ return "SUCCESS: Password has been changed."
582
+
583
+ def forgot_password(self, email: str, template: Optional[Dict[str, str]] = None) -> str:
584
+ """Sends a password reset code to the account's e-mail. Then call reset_password()."""
585
+ self._ensure_connection()
586
+ email = validate_email(email)
587
+ metadata = None
588
+ if template is not None:
589
+ if not isinstance(template, dict):
590
+ raise _p('"template" should be type: <object>.')
591
+ if "verification" in template:
592
+ raise _p('"template.verification" is not an option of forgot_password(). Use "template.forgot_password" (template message_id).')
593
+ if "forgot_password" in template:
594
+ if not isinstance(template["forgot_password"], str) or not template["forgot_password"]:
595
+ raise _p('"template.forgot_password" should be a non-empty <string> (template message_id).')
596
+ metadata = {"template_forgot_password": template["forgot_password"]}
597
+ try:
598
+ self._user_pool().call_public("ForgotPassword", Username=self._cognito_name(email), ClientMetadata=metadata)
599
+ except CognitoError as err:
600
+ parsed = _parsed_cognito_error(err)
601
+ code = {"UserNotFoundException": "NOT_EXISTS", "InvalidParameterException": "INVALID_PARAMETER", "NotAuthorizedException": "INVALID_REQUEST",
602
+ "LimitExceededException": "REQUEST_EXCEED", "TooManyRequestsException": "REQUEST_EXCEED",
603
+ "CodeDeliveryFailureException": "CODE_DELIVERY_FAILURE"}.get(err.code, parsed.code or err.code or "ERROR")
604
+ raise SkapiError(parsed.message, code, err) from None
605
+ return "SUCCESS: Verification code has been sent."
606
+
607
+ def reset_password(self, email: str, code: Any, new_password: str) -> str:
608
+ self._ensure_connection()
609
+ email = validate_email(email)
610
+ if isinstance(code, bool) or not isinstance(code, (str, int)):
611
+ raise _p(f'{_jd(code)} is invalid in "code". allowed types or values are: Type<number>, Type<string>.')
612
+ validate_password(new_password)
613
+ try:
614
+ self._user_pool().call_public("ConfirmForgotPassword", Username=self._cognito_name(email), ConfirmationCode=str(code), Password=new_password)
615
+ except CognitoError as err:
616
+ raise SkapiError(err.message or "Failed to reset password.", err.code or "ERROR", err) from None
617
+ return "SUCCESS: New password has been set."
618
+
619
+ def verify_email(self, code: Optional[str] = None, template: Optional[Dict[str, str]] = None) -> str:
620
+ """Without code: sends a verification code to the user's e-mail. With code: verifies it."""
621
+ self._ensure_connection()
622
+ if not self._signed_in():
623
+ raise SkapiError("The user has to be logged in.", "INVALID_REQUEST")
624
+ self._refuse_anonymous("verify an e-mail")
625
+ if "email" not in self._user:
626
+ raise SkapiError("No e-mail to verify", "INVALID_REQUEST")
627
+ if self._user.get("email_verified"):
628
+ return 'SUCCESS: "email" is verified.'
629
+ if code is not None and not isinstance(code, str):
630
+ raise _p(f'{_jd(code)} is invalid in "code". allowed type or value is: Type<string>.')
631
+ metadata = None
632
+ if template and "verification" in template:
633
+ if not isinstance(template["verification"], str) or not template["verification"]:
634
+ raise _p('"template.verification" should be a non-empty <string> (template message_id).')
635
+ metadata = {"template_verification": template["verification"]}
636
+ try:
637
+ if code:
638
+ self._user_pool().call("VerifyUserAttribute", self._access_token(), AttributeName="email", Code=code)
639
+ self._refresh_session()
640
+ self._user["email_verified"] = True
641
+ return 'SUCCESS: "email" is verified.'
642
+ self._user_pool().call("GetUserAttributeVerificationCode", self._access_token(), AttributeName="email", ClientMetadata=metadata)
643
+ return "SUCCESS: Verification code has been sent."
644
+ except CognitoError as err:
645
+ raise SkapiError(err.message or "Failed to request verification code.", err.code, err) from None
646
+
647
+ def last_verified_email(self, revert: Optional[bool] = None):
648
+ self._require_session()
649
+ self._refuse_anonymous("change their e-mail")
650
+ body = {} if revert is None else {"revert": revert}
651
+ reply = self._call("last-verified-email", body, auth=True)
652
+ if isinstance(reply, str) and "SUCCESS" in reply:
653
+ self._refresh_session()
654
+ return self.user
655
+ return reply
656
+
657
+ # ---- OpenID and anonymous -------------------------------------------------------------------
658
+
659
+ def open_id_login(self, token: str, id: str, merge: Any = None, template: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
660
+ """Signs in with a token from your OpenID provider, through the OpenID logger set up as `id`."""
661
+ self._ensure_connection()
662
+ body: Dict[str, Any] = {"token": _string("token")(token), "id": _string("id")(id)}
663
+ if merge is not None:
664
+ if isinstance(merge, str):
665
+ merge = [merge]
666
+ if isinstance(merge, list):
667
+ if not all(isinstance(m, str) for m in merge):
668
+ raise _p('"merge" array items should be type: <string>.')
669
+ elif not isinstance(merge, bool):
670
+ raise _p('"merge" should be type: <boolean | string[]>.')
671
+ body["merge"] = merge
672
+ if template is not None:
673
+ if not isinstance(template, dict):
674
+ raise _p('"template" should be type: <object>.')
675
+ if "welcome" in template:
676
+ if not isinstance(template["welcome"], str) or not template["welcome"]:
677
+ raise _p('"template.welcome" should be a non-empty <string> (template message_id).')
678
+ body["template_welcome"] = template["welcome"]
679
+ reply = self._call("openid-logger", body)
680
+ logger = str(reply.get("logger", "")).split("#")
681
+ profile = self._authenticate(f"{self.service}-{logger[0]}", logger[1] if len(logger) > 1 else "", raw=True, is_openid=True)
682
+ return {"userProfile": profile, "openid": reply.get("openid")}
683
+
684
+ def anonymous_login(self) -> Dict[str, Any]:
685
+ """A temporary account without e-mail or password, deleted 30 minutes after this object stops keeping it alive."""
686
+ self._ensure_connection()
687
+ if self._signed_in():
688
+ if self._user.get("anonymous"):
689
+ self._start_anonymous_keep_alive()
690
+ return self.user
691
+ raise SkapiError("A user is already logged in. Log out first.", "INVALID_REQUEST")
692
+ creds = self._call("anonymous-login", {})
693
+ profile = self._authenticate(creds["username"], creds["password"], raw=True)
694
+ self._start_anonymous_keep_alive()
695
+ return profile
696
+
697
+ def verify_anonymous_session(self) -> Optional[Dict[str, Any]]:
698
+ """
699
+ For a temporary account restored from storage: asks the server whether it still exists.
700
+ Returns the profile, or None (and signs out) when the account was already deleted.
701
+ Any other user is returned as is, without a request.
702
+ """
703
+ self._ensure_connection()
704
+ self._restore()
705
+ if not (self._user and self._user.get("anonymous")):
706
+ return self.user
707
+ try:
708
+ self._call("anonymous-session", {}, auth=True)
709
+ except SkapiError as err:
710
+ if err.code == "NOT_EXISTS":
711
+ self._clear_session()
712
+ return None
713
+ return self.user
714
+
715
+ def _start_anonymous_keep_alive(self, beat_now: bool = False) -> None:
716
+ self._stop_anonymous_keep_alive()
717
+
718
+ def beat():
719
+ if not (self._user and self._user.get("anonymous")):
720
+ return
721
+ try:
722
+ self._call("anonymous-session", {}, auth=True)
723
+ except SkapiError as err:
724
+ if err.code == "NOT_EXISTS":
725
+ self._clear_session()
726
+ return
727
+ self._start_anonymous_keep_alive()
728
+
729
+ timer = threading.Timer(0 if beat_now else ANONYMOUS_KEEPALIVE_SECONDS, beat)
730
+ timer.daemon = True
731
+ timer.start()
732
+ self._anonymous_timer = timer
733
+
734
+ def _stop_anonymous_keep_alive(self) -> None:
735
+ timer = getattr(self, "_anonymous_timer", None)
736
+ if timer:
737
+ timer.cancel()
738
+ self._anonymous_timer = None
739
+
740
+ # ---- authenticator app MFA ----------------------------------------------------------------
741
+
742
+ def _mfa_user(self, what: str) -> str:
743
+ self._require_session()
744
+ self._refuse_anonymous(what)
745
+ return self._access_token()
746
+
747
+ def setup_mfa(self, issuer: Optional[str] = None, account_name: Optional[str] = None) -> Dict[str, str]:
748
+ """Starts two-step login setup: returns {"secret", "uri"}. Show uri as a QR code, then call enable_mfa(code)."""
749
+ token = self._mfa_user("set up MFA")
750
+ try:
751
+ secret = self._user_pool().call("AssociateSoftwareToken", token)["SecretCode"]
752
+ except CognitoError as err:
753
+ raise _parsed_cognito_error(err) from None
754
+ conn = self.connection or {}
755
+ issuer = (issuer or conn.get("service_name") or self.service or "").replace(":", " ").strip()
756
+ u = self._user or {}
757
+ account = (account_name or u.get("email") or u.get("username") or u.get("user_id") or "").replace(":", " ").strip()
758
+ enc = lambda s: quote(s, safe="-_.!~*'()")
759
+ label = f"{enc(issuer)}:{enc(account)}" if issuer else enc(account)
760
+ uri = f"otpauth://totp/{label}?secret={secret}" + (f"&issuer={enc(issuer)}" if issuer else "") + "&algorithm=SHA1&digits=6&period=30"
761
+ return {"secret": secret, "uri": uri}
762
+
763
+ def enable_mfa(self, code: str) -> str:
764
+ code = _mfa_code(code)
765
+ token = self._mfa_user("turn on MFA")
766
+ try:
767
+ self._user_pool().call("VerifySoftwareToken", token, UserCode=code)
768
+ except CognitoError as err:
769
+ if err.code == "SoftwareTokenMFANotFoundException" or (err.code == "InvalidParameterException" and re.search(r"software token", err.message or "", re.I)):
770
+ raise SkapiError("Call setup_mfa() first.", "INVALID_REQUEST", err) from None
771
+ if err.code in ("EnableSoftwareTokenMFAException", "CodeMismatchException"):
772
+ raise SkapiError("Incorrect authenticator code.", "INVALID_CODE", err) from None
773
+ if err.code in ("TooManyRequestsException", "LimitExceededException"):
774
+ raise SkapiError("Too many attempts. Please try again later.", "REQUEST_EXCEED", err) from None
775
+ raise _parsed_cognito_error(err) from None
776
+ try:
777
+ self._user_pool().call("SetUserMFAPreference", token, SoftwareTokenMfaSettings={"Enabled": True, "PreferredMfa": True})
778
+ except CognitoError as err:
779
+ raise _parsed_cognito_error(err) from None
780
+ return "SUCCESS: MFA has been enabled."
781
+
782
+ def disable_mfa(self) -> str:
783
+ token = self._mfa_user("turn off MFA")
784
+ try:
785
+ self._user_pool().call("SetUserMFAPreference", token, SoftwareTokenMfaSettings={"Enabled": False, "PreferredMfa": False})
786
+ except CognitoError as err:
787
+ raise _parsed_cognito_error(err) from None
788
+ return "SUCCESS: MFA has been disabled."
789
+
790
+ def get_mfa_status(self) -> Dict[str, bool]:
791
+ token = self._mfa_user("use MFA")
792
+ try:
793
+ data = self._user_pool().call("GetUser", token)
794
+ except CognitoError as err:
795
+ raise _parsed_cognito_error(err) from None
796
+ return {"enabled": "SOFTWARE_TOKEN_MFA" in (data.get("UserMFASettingList") or [])}
797
+
798
+ # ---- users ----------------------------------------------------------------------------------
799
+
800
+ def get_users(self, params: Optional[Dict[str, Any]] = None, fetch_options: Optional[dict] = None) -> dict:
801
+ """Searches the project's users by one profile field. Signed-in users only."""
802
+ fetch_options = dict(fetch_options or {})
803
+ if not params:
804
+ params = {"searchFor": "timestamp", "condition": ">", "value": 0}
805
+ fetch_options["ascending"] = False
806
+ params = dict(params)
807
+ fields = ["user_id", "name", "email", "phone_number", "address", "gender", "birthdate", "locale", "subscribers", "timestamp", "access_group", "approved"]
808
+ search_for = params.get("searchFor")
809
+ if "searchFor" not in params:
810
+ raise _p('Key "searchFor" is required.')
811
+ if "value" not in params:
812
+ raise _p('Key "value" is required.')
813
+ if search_for == "":
814
+ raise _p('"searchFor" should not be an empty string.')
815
+ if search_for not in fields:
816
+ raise _p(f'{_jd(search_for)} is invalid in "searchFor". allowed types or values are: ' + ", ".join(_jd(f) for f in fields) + ".")
817
+ conditions = [">", ">=", "=", "<", "<=", "gt", "gte", "eq", "lt", "lte"]
818
+ condition = params.get("condition", "=")
819
+ if condition not in conditions:
820
+ condition = "="
821
+
822
+ def check(v, what):
823
+ if search_for == "user_id":
824
+ if not isinstance(v, str) or not _UUID.match(v):
825
+ raise _p("User ID is invalid.")
826
+ elif search_for == "locale":
827
+ if not isinstance(v, str) or len(v) > 5:
828
+ raise _p('Value of "locale" should be a country code.')
829
+ elif search_for == "birthdate":
830
+ _birthdate(v)
831
+ elif search_for in ("subscribers", "timestamp", "access_group"):
832
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
833
+ raise _p(f'{what} does not match the type of "{search_for}" index.')
834
+ elif not isinstance(v, str):
835
+ raise _p(f'{what} does not match the type of "{search_for}" index.')
836
+ return v
837
+
838
+ value = params["value"]
839
+ if isinstance(value, list):
840
+ value = [check(v, "Value") for v in value]
841
+ else:
842
+ check(value, "Value")
843
+ body = {"searchFor": search_for, "value": value, "condition": condition}
844
+ if "range" in params:
845
+ check(params["range"], "Range")
846
+ body["range"] = params["range"]
847
+ if condition != "=" and "range" in params:
848
+ raise _p("Conditions does not apply on range search.")
849
+ if isinstance(value, list) and (condition != "=" or params.get("range")):
850
+ raise _p(f'Conditions are not allowed on a list of "{search_for}" values. Search for a single value to use a condition or range.')
851
+ if value == "":
852
+ raise _p("Value should not be an empty string.")
853
+ return self._call("get-users", body, auth=True, fetch_options=fetch_options)
854
+
855
+ # ---- tickets --------------------------------------------------------------------------------
856
+
857
+ def consume_ticket(self, ticket_id: str, method: str = "POST", data: Any = None, auth: bool = False) -> Any:
858
+ """Calls a ticket of the project (set up on skapi.com) with `data`. Returns its receipt or answer."""
859
+ from ._social import map_ticket
860
+ self._ensure_connection()
861
+ if not ticket_id:
862
+ raise _p("Ticket ID is required.")
863
+ if not isinstance(ticket_id, str) or not re.match(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$", ticket_id):
864
+ raise _p('Invalid "ticket_id". Use letters, digits, "_" and "-" (up to 64 chars, starting with a letter or digit).')
865
+ if not method:
866
+ raise _p('Method is required. Should be either "GET" or "POST"')
867
+ method = str(method).upper()
868
+ if method not in ("GET", "POST"):
869
+ raise _p('Method should be either "GET" or "POST".')
870
+ if auth and method == "GET":
871
+ raise _p("Signed-in consumption is POST only.")
872
+ route = "tpa" if auth else ("tg" if method == "GET" else "tp")
873
+ url = f"https://{self.service[:4]}.skapi.dev/{route}/{self.service}/{ticket_id}"
874
+ token = self._fresh_id_token() if auth else None
875
+ reply = self._requester.request(url, data or {}, method=method, token=token, ignore_service=True)
876
+ if isinstance(reply, dict) and "stage" in reply:
877
+ raise SkapiError(reply.get("message") or "Ticket failed.", reply.get("code") or "ERROR", reply)
878
+ if isinstance(reply, dict) and isinstance(reply.get("tkid"), str):
879
+ return map_ticket(reply)
880
+ return reply