amazon-auth 0.2.6__tar.gz → 0.3.0__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.
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/PKG-INFO +1 -1
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazon_auth.egg-info/PKG-INFO +1 -1
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/__init__.py +1 -1
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/conf.py +96 -10
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/browser/playwright.py +30 -34
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/session.py +31 -1
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/util.py +13 -4
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_session.py +116 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_util.py +10 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/LICENSE +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/README.md +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazon_auth.egg-info/SOURCES.txt +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazon_auth.egg-info/dependency_links.txt +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazon_auth.egg-info/requires.txt +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazon_auth.egg-info/top_level.txt +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/cli.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/constants.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/__init__.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/browser/__init__.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/waf/__init__.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/waf/anticaptcha.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/waf/base.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/waf/capsolver.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/contrib/waf/twocaptcha.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/exception.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/forms.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/py.typed +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/region_data.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/amazonauth/selectors.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/pyproject.toml +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/setup.cfg +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_cli.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_conf.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_constants.py +0 -0
- {amazon_auth-0.2.6 → amazon_auth-0.3.0}/tests/test_package.py +0 -0
|
@@ -4,9 +4,10 @@ __license__ = "MIT"
|
|
|
4
4
|
import inspect
|
|
5
5
|
import logging
|
|
6
6
|
import os
|
|
7
|
+
import re
|
|
7
8
|
import threading
|
|
8
9
|
import warnings
|
|
9
|
-
from typing import Any, Dict, Optional, Set, Union
|
|
10
|
+
from typing import Any, Dict, List, Optional, Set, Union
|
|
10
11
|
from urllib.parse import urlparse
|
|
11
12
|
|
|
12
13
|
import yaml
|
|
@@ -29,6 +30,16 @@ ENVIRONMENT_VARIABLE_PREFIX = "AMAZON_"
|
|
|
29
30
|
#: The Amazon site whose session is kept in the default ``cookie_jar_path`` itself, rather than in a jar of its own.
|
|
30
31
|
DEFAULT_COOKIE_JAR_SITE = "amazon.com"
|
|
31
32
|
|
|
33
|
+
#: The account whose sessions are kept beside the default ``cookie_jar_path`` itself, rather than in a directory of
|
|
34
|
+
#: its own, and the one used when no ``account`` is given.
|
|
35
|
+
DEFAULT_ACCOUNT = "default"
|
|
36
|
+
|
|
37
|
+
#: The directory, beside the default ``cookie_jar_path``, where each other account's sessions are kept, in a
|
|
38
|
+
#: directory named for the account.
|
|
39
|
+
ACCOUNTS_DIRECTORY = "accounts"
|
|
40
|
+
|
|
41
|
+
ACCOUNT_NAME_PATTERN = re.compile(r"^[a-z0-9_-]+$")
|
|
42
|
+
|
|
32
43
|
|
|
33
44
|
class AmazonAuthConfig:
|
|
34
45
|
"""
|
|
@@ -87,6 +98,7 @@ class AmazonAuthConfig:
|
|
|
87
98
|
|
|
88
99
|
self._validate_bs4_parser()
|
|
89
100
|
self._validate_class_paths()
|
|
101
|
+
self._validate_account()
|
|
90
102
|
|
|
91
103
|
#: The :class:`~amazonauth.constants.AuthConstants` in use, rebuilt when the domain changes.
|
|
92
104
|
self.constants: Any
|
|
@@ -254,6 +266,23 @@ class AmazonAuthConfig:
|
|
|
254
266
|
source = self._environment if "bs4_parser" in self._environment else self._data
|
|
255
267
|
source["bs4_parser"] = "html.parser"
|
|
256
268
|
|
|
269
|
+
def _validate_account(self) -> None:
|
|
270
|
+
account = self.account
|
|
271
|
+
if not ACCOUNT_NAME_PATTERN.match(account):
|
|
272
|
+
raise AmazonAuthError(f"\"{account}\" isn't a name an account can have. An account's name is letters, "
|
|
273
|
+
"digits, \"-\" and \"_\".")
|
|
274
|
+
if account != DEFAULT_ACCOUNT and self._get("cookie_jar_path") != self._default_cookie_jar_path():
|
|
275
|
+
raise AmazonAuthError(f"The \"{account}\" account can't be used with the cookie_jar_path setting, since "
|
|
276
|
+
"every account's session would be kept in it. Leave it unset for each account to "
|
|
277
|
+
"have its own.")
|
|
278
|
+
|
|
279
|
+
def _has_cookie_jar(self,
|
|
280
|
+
directory: str) -> bool:
|
|
281
|
+
root, extension = os.path.splitext(os.path.basename(self._default_cookie_jar_path()))
|
|
282
|
+
return os.path.isdir(directory) and any(
|
|
283
|
+
name == f"{root}{extension}" or (name.startswith(f"{root}.") and name.endswith(extension))
|
|
284
|
+
for name in os.listdir(directory))
|
|
285
|
+
|
|
257
286
|
def _instantiate_constants(self) -> Any:
|
|
258
287
|
constants_cls = self._load_configured_class("constants_class")
|
|
259
288
|
# Pass ``self`` only when the constants class accepts a config arg, to keep backward
|
|
@@ -274,25 +303,80 @@ class AmazonAuthConfig:
|
|
|
274
303
|
self._data["domain"] = domain
|
|
275
304
|
self.constants = self._instantiate_constants()
|
|
276
305
|
|
|
306
|
+
def set_account(self,
|
|
307
|
+
account: Optional[str]) -> None:
|
|
308
|
+
"""
|
|
309
|
+
Set the active Amazon account, whose sessions are read and saved.
|
|
310
|
+
|
|
311
|
+
:param account: The account's name, or ``None`` for the ``default`` account.
|
|
312
|
+
:raises AmazonAuthError: If the name isn't one an account can have, or ``cookie_jar_path`` is set.
|
|
313
|
+
"""
|
|
314
|
+
previous_account = self._data.get("account")
|
|
315
|
+
self._data["account"] = account
|
|
316
|
+
try:
|
|
317
|
+
self._validate_account()
|
|
318
|
+
except AmazonAuthError:
|
|
319
|
+
self._data["account"] = previous_account
|
|
320
|
+
raise
|
|
321
|
+
|
|
277
322
|
@property
|
|
278
323
|
def site(self) -> str:
|
|
279
324
|
"""The active Amazon site, the host of the ``domain`` without ``www.`` (e.g. ``amazon.de``)."""
|
|
280
325
|
return (urlparse(self.constants.BASE_URL).hostname or "").removeprefix("www.")
|
|
281
326
|
|
|
327
|
+
@property
|
|
328
|
+
def account(self) -> str:
|
|
329
|
+
"""The active Amazon account's name, the ``account`` set (in lowercase), or else ``default``."""
|
|
330
|
+
account = self._get("account")
|
|
331
|
+
return DEFAULT_ACCOUNT if account in (None, "") else str(account).lower()
|
|
332
|
+
|
|
333
|
+
def accounts(self) -> List[str]:
|
|
334
|
+
"""
|
|
335
|
+
Get the active account, then every other account with a saved session (a cookie jar) on any site, signed in
|
|
336
|
+
or not. With an explicit ``cookie_jar_path``, there's only the active account.
|
|
337
|
+
|
|
338
|
+
:return: The accounts' names.
|
|
339
|
+
"""
|
|
340
|
+
accounts = [self.account]
|
|
341
|
+
default_cookie_jar_path = self._default_cookie_jar_path()
|
|
342
|
+
if self._get("cookie_jar_path") != default_cookie_jar_path:
|
|
343
|
+
return accounts
|
|
344
|
+
|
|
345
|
+
config_dir = os.path.dirname(default_cookie_jar_path)
|
|
346
|
+
account_dirs = {DEFAULT_ACCOUNT: config_dir}
|
|
347
|
+
accounts_dir = os.path.join(config_dir, ACCOUNTS_DIRECTORY)
|
|
348
|
+
if os.path.isdir(accounts_dir):
|
|
349
|
+
for name in sorted(os.listdir(accounts_dir)):
|
|
350
|
+
if name != DEFAULT_ACCOUNT and ACCOUNT_NAME_PATTERN.match(name):
|
|
351
|
+
account_dirs[name] = os.path.join(accounts_dir, name)
|
|
352
|
+
|
|
353
|
+
for account, directory in account_dirs.items():
|
|
354
|
+
if account not in accounts and self._has_cookie_jar(directory):
|
|
355
|
+
accounts.append(account)
|
|
356
|
+
|
|
357
|
+
return accounts
|
|
358
|
+
|
|
282
359
|
@property
|
|
283
360
|
def cookie_jar_path(self) -> str:
|
|
284
361
|
"""
|
|
285
|
-
The path the session for the active ``domain`` is persisted to, since each Amazon site
|
|
286
|
-
With the default ``cookie_jar_path``, the ``amazon.com``
|
|
287
|
-
other site's beside it, named for the site (e.g.
|
|
288
|
-
|
|
362
|
+
The path the session for the active ``domain`` and ``account`` is persisted to, since each Amazon site and
|
|
363
|
+
account has its own sign-in. With the default ``cookie_jar_path``, the default account's ``amazon.com``
|
|
364
|
+
session is kept there (``cookies.json``), and every other site's beside it, named for the site (e.g.
|
|
365
|
+
``cookies.amazon.de.json``). Each other account's are kept the same way, in a directory of their own (e.g.
|
|
366
|
+
``accounts/spouse/cookies.json``). Any other ``cookie_jar_path`` is used as-is, whatever the site.
|
|
289
367
|
"""
|
|
290
368
|
cookie_jar_path = self._get("cookie_jar_path")
|
|
291
|
-
if cookie_jar_path != self._default_cookie_jar_path()
|
|
369
|
+
if cookie_jar_path != self._default_cookie_jar_path():
|
|
292
370
|
return cookie_jar_path
|
|
293
371
|
|
|
294
|
-
|
|
295
|
-
|
|
372
|
+
directory, filename = os.path.split(cookie_jar_path)
|
|
373
|
+
if self.account != DEFAULT_ACCOUNT:
|
|
374
|
+
directory = os.path.join(directory, ACCOUNTS_DIRECTORY, self.account)
|
|
375
|
+
if self.site != DEFAULT_COOKIE_JAR_SITE:
|
|
376
|
+
root, extension = os.path.splitext(filename)
|
|
377
|
+
filename = f"{root}.{self.site}{extension}"
|
|
378
|
+
|
|
379
|
+
return os.path.join(directory, filename)
|
|
296
380
|
|
|
297
381
|
@cookie_jar_path.setter
|
|
298
382
|
def cookie_jar_path(self,
|
|
@@ -303,10 +387,11 @@ class AmazonAuthConfig:
|
|
|
303
387
|
def shared_cookie_jar_path(self) -> Optional[str]:
|
|
304
388
|
"""
|
|
305
389
|
The default ``cookie_jar_path``, which every site's session was persisted to before each site had its own,
|
|
306
|
-
when the active ``domain`` now has a jar of its own (see :attr:`cookie_jar_path`), otherwise ``None``.
|
|
390
|
+
when the active ``domain`` now has a jar of its own (see :attr:`cookie_jar_path`), otherwise ``None``. Only
|
|
391
|
+
the default account had sessions then, so it's always ``None`` for any other account.
|
|
307
392
|
"""
|
|
308
393
|
shared_cookie_jar_path = self._get("cookie_jar_path")
|
|
309
|
-
if self.cookie_jar_path == shared_cookie_jar_path:
|
|
394
|
+
if self.account != DEFAULT_ACCOUNT or self.cookie_jar_path == shared_cookie_jar_path:
|
|
310
395
|
return None
|
|
311
396
|
|
|
312
397
|
return shared_cookie_jar_path
|
|
@@ -348,6 +433,7 @@ class AmazonAuthConfig:
|
|
|
348
433
|
try:
|
|
349
434
|
self._validate_bs4_parser()
|
|
350
435
|
self._validate_class_paths()
|
|
436
|
+
self._validate_account()
|
|
351
437
|
if key in ("constants_class", "selectors_class"):
|
|
352
438
|
module_path, class_name = self._class_path(key).rsplit(".", 1)
|
|
353
439
|
util.load_class(module_path.split("."), class_name)
|
|
@@ -40,17 +40,6 @@ SIGN_IN_SETTLE_MS = 2000
|
|
|
40
40
|
SIGN_IN_PREFILL_TIMEOUT_MS = 5000
|
|
41
41
|
|
|
42
42
|
|
|
43
|
-
def _jar_cookie_attributes(pw_cookie: Dict[str, Any]) -> Dict[str, Any]:
|
|
44
|
-
"""
|
|
45
|
-
The attributes of a browser cookie, as the session's cookie jar takes them. ``secure`` is kept, so a cookie only
|
|
46
|
-
sent over ``https`` in the browser is only sent over ``https`` by the session too.
|
|
47
|
-
"""
|
|
48
|
-
expires = pw_cookie.get("expires", -1)
|
|
49
|
-
return {"domain": pw_cookie.get("domain"), "path": pw_cookie.get("path", "/"),
|
|
50
|
-
"secure": bool(pw_cookie.get("secure", False)),
|
|
51
|
-
"expires": int(expires) if expires and expires > 0 else None}
|
|
52
|
-
|
|
53
|
-
|
|
54
43
|
class PlaywrightBrowserLauncher:
|
|
55
44
|
"""
|
|
56
45
|
Launches the browser the config selects, from whatever Playwright supports. ``browser`` is either a browser that's
|
|
@@ -74,13 +63,15 @@ class PlaywrightBrowserLauncher:
|
|
|
74
63
|
def launch(self,
|
|
75
64
|
pw: Any,
|
|
76
65
|
headless: bool,
|
|
77
|
-
args: Optional[List[str]] = None
|
|
66
|
+
args: Optional[List[str]] = None,
|
|
67
|
+
env: Optional[Dict[str, str]] = None) -> Any:
|
|
78
68
|
"""
|
|
79
69
|
Launch the browser the config selects.
|
|
80
70
|
|
|
81
71
|
:param pw: The running Playwright instance.
|
|
82
72
|
:param headless: Whether to launch the browser without a window.
|
|
83
73
|
:param args: Command line arguments to launch the browser with, beside Playwright's own.
|
|
74
|
+
:param env: The browser child's environment, or ``None`` to inherit the process environment.
|
|
84
75
|
:return: The launched Playwright ``Browser``.
|
|
85
76
|
:raises AmazonAuthBrowserNotInstalledError: If no browser is installed to launch.
|
|
86
77
|
:raises AmazonAuthError: If the browser can't be launched.
|
|
@@ -90,9 +81,9 @@ class PlaywrightBrowserLauncher:
|
|
|
90
81
|
browser_name = self.config.browser
|
|
91
82
|
executable_path = self.config.browser_executable_path
|
|
92
83
|
if not browser_name and not executable_path:
|
|
93
|
-
return self._launch_default(pw, headless, args)
|
|
84
|
+
return self._launch_default(pw, headless, args, env)
|
|
94
85
|
|
|
95
|
-
launch_options = self._launch_options(headless, args)
|
|
86
|
+
launch_options = self._launch_options(headless, args, env)
|
|
96
87
|
channel = None
|
|
97
88
|
browser_type = self._browser_types(pw).get(browser_name or self.FALLBACK_BROWSER_TYPE)
|
|
98
89
|
if browser_type is None:
|
|
@@ -143,10 +134,11 @@ class PlaywrightBrowserLauncher:
|
|
|
143
134
|
def _launch_default(self,
|
|
144
135
|
pw: Any,
|
|
145
136
|
headless: bool,
|
|
146
|
-
args: Optional[List[str]]
|
|
137
|
+
args: Optional[List[str]],
|
|
138
|
+
env: Optional[Dict[str, str]]) -> Any:
|
|
147
139
|
from playwright.sync_api import Error as PlaywrightError # type: ignore[import-not-found]
|
|
148
140
|
|
|
149
|
-
launch_options = self._launch_options(headless, args)
|
|
141
|
+
launch_options = self._launch_options(headless, args, env)
|
|
150
142
|
for channel in (self.DEFAULT_BROWSER_CHANNEL, self.FALLBACK_BROWSER_CHANNEL):
|
|
151
143
|
try:
|
|
152
144
|
return pw.chromium.launch(channel=channel, **launch_options)
|
|
@@ -173,10 +165,13 @@ class PlaywrightBrowserLauncher:
|
|
|
173
165
|
|
|
174
166
|
@staticmethod
|
|
175
167
|
def _launch_options(headless: bool,
|
|
176
|
-
args: Optional[List[str]]
|
|
168
|
+
args: Optional[List[str]],
|
|
169
|
+
env: Optional[Dict[str, str]]) -> Dict[str, Any]:
|
|
177
170
|
launch_options: Dict[str, Any] = {"headless": headless}
|
|
178
171
|
if args:
|
|
179
172
|
launch_options["args"] = args
|
|
173
|
+
if env is not None:
|
|
174
|
+
launch_options["env"] = env
|
|
180
175
|
|
|
181
176
|
return launch_options
|
|
182
177
|
|
|
@@ -371,9 +366,7 @@ class PlaywrightAuthForm(AuthForm):
|
|
|
371
366
|
def _harvest_cookies(self, context: Any) -> None:
|
|
372
367
|
if not self.amazon_session:
|
|
373
368
|
return # pragma: no cover
|
|
374
|
-
|
|
375
|
-
self.amazon_session.session.cookies.set(pw_cookie["name"], pw_cookie["value"],
|
|
376
|
-
**_jar_cookie_attributes(pw_cookie))
|
|
369
|
+
self.amazon_session._load_cookie_jar_data(context.cookies())
|
|
377
370
|
|
|
378
371
|
def _save_debug_snapshot(self, page: Any, output_dir: Optional[str], name: str) -> None:
|
|
379
372
|
if not output_dir:
|
|
@@ -904,13 +897,14 @@ class PlaywrightBrowserLogin:
|
|
|
904
897
|
f"Install it with: `pip install {self.config.PACKAGE_NAME}[browser]`"
|
|
905
898
|
) from e
|
|
906
899
|
|
|
907
|
-
self.
|
|
900
|
+
env = self.launch_env()
|
|
901
|
+
self._require_display(env)
|
|
908
902
|
|
|
909
903
|
constants = self.config.constants
|
|
910
904
|
sign_in_url = f"{constants.SIGN_IN_URL}?{urlencode(constants.SIGN_IN_QUERY_PARAMS)}"
|
|
911
905
|
|
|
912
906
|
with sync_playwright() as pw:
|
|
913
|
-
browser = PlaywrightBrowserLauncher(self.config).launch(pw, self.headless, self.launch_args())
|
|
907
|
+
browser = PlaywrightBrowserLauncher(self.config).launch(pw, self.headless, self.launch_args(), env=env)
|
|
914
908
|
|
|
915
909
|
try:
|
|
916
910
|
context = self.new_context(browser)
|
|
@@ -938,6 +932,15 @@ class PlaywrightBrowserLogin:
|
|
|
938
932
|
"""
|
|
939
933
|
return None
|
|
940
934
|
|
|
935
|
+
def launch_env(self) -> Optional[Dict[str, str]]:
|
|
936
|
+
"""
|
|
937
|
+
Hook for the environment to launch the browser with. By default, the browser inherits this process's. A
|
|
938
|
+
mapping replaces it, so copy ``os.environ`` first if the browser should inherit other variables.
|
|
939
|
+
|
|
940
|
+
:return: The child's environment, or ``None`` to inherit it.
|
|
941
|
+
"""
|
|
942
|
+
return None
|
|
943
|
+
|
|
941
944
|
def new_context(self,
|
|
942
945
|
browser: Any) -> Any:
|
|
943
946
|
"""
|
|
@@ -986,8 +989,9 @@ class PlaywrightBrowserLogin:
|
|
|
986
989
|
except Exception as e:
|
|
987
990
|
logger.debug(f"Skipped pre-filling the username in the browser: {e}")
|
|
988
991
|
|
|
989
|
-
def _require_display(self
|
|
990
|
-
|
|
992
|
+
def _require_display(self,
|
|
993
|
+
env: Optional[Dict[str, str]]) -> None:
|
|
994
|
+
if not self.headless and not has_display(env):
|
|
991
995
|
raise AmazonAuthError("Signing in with a browser requires a display, and this machine doesn't have one.")
|
|
992
996
|
|
|
993
997
|
def wait_for_sign_in(self,
|
|
@@ -1027,21 +1031,13 @@ class PlaywrightBrowserLogin:
|
|
|
1027
1031
|
|
|
1028
1032
|
def _amazon_cookies(self,
|
|
1029
1033
|
cookies: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
return [cookie for cookie in cookies if self._is_domain_or_subdomain(cookie["domain"], base_domain)]
|
|
1033
|
-
|
|
1034
|
-
@staticmethod
|
|
1035
|
-
def _is_domain_or_subdomain(domain: str,
|
|
1036
|
-
parent_domain: str) -> bool:
|
|
1037
|
-
return f".{domain.lstrip('.')}".endswith(f".{parent_domain}")
|
|
1034
|
+
return [cookie for cookie in cookies if self.amazon_session._is_site_cookie(cookie)]
|
|
1038
1035
|
|
|
1039
1036
|
def _harvest_cookies(self,
|
|
1040
1037
|
context: Any) -> None:
|
|
1041
1038
|
cookie_jar = self.amazon_session.session.cookies
|
|
1042
1039
|
cookie_jar.clear()
|
|
1043
|
-
|
|
1044
|
-
cookie_jar.set(cookie["name"], cookie["value"], **_jar_cookie_attributes(cookie))
|
|
1040
|
+
self.amazon_session._load_cookie_jar_data(self._amazon_cookies(context.cookies()))
|
|
1045
1041
|
|
|
1046
1042
|
def _verify_session(self) -> None:
|
|
1047
1043
|
try:
|
|
@@ -361,6 +361,35 @@ class AmazonSession:
|
|
|
361
361
|
|
|
362
362
|
return True
|
|
363
363
|
|
|
364
|
+
def import_cookies(self,
|
|
365
|
+
cookies: List[Dict[str, Any]],
|
|
366
|
+
verify: bool = True) -> None:
|
|
367
|
+
"""
|
|
368
|
+
Replace this session's cookies with the given ones for the configured site, and persist them. Accepts cookies
|
|
369
|
+
as Playwright's ``BrowserContext.cookies()`` returns them.
|
|
370
|
+
|
|
371
|
+
By default, Amazon is asked whether it accepts the session, as :func:`check_session` does with ``verify``,
|
|
372
|
+
and ``is_authenticated`` is set to ``True`` if it does. If it doesn't, they still replace this session's
|
|
373
|
+
cookies, and may already have been saved. With ``verify=False``, no request is made.
|
|
374
|
+
|
|
375
|
+
:param cookies: Cookies with name, value and domain, and optional path, secure and expires attributes.
|
|
376
|
+
:param verify: Whether to verify the imported session with :func:`check_session`.
|
|
377
|
+
:raises AmazonAuthSignInError: If verification finds no authenticated session or Amazon rejects it.
|
|
378
|
+
:raises AmazonAuthError: If the verification request fails.
|
|
379
|
+
"""
|
|
380
|
+
self.is_authenticated = False
|
|
381
|
+
self._sign_in_required = False
|
|
382
|
+
self.session.cookies.clear()
|
|
383
|
+
self._load_cookie_jar_data([cookie for cookie in cookies if self._is_site_cookie(cookie)])
|
|
384
|
+
|
|
385
|
+
if verify:
|
|
386
|
+
if not self.check_session(verify=True):
|
|
387
|
+
raise AmazonAuthSignInError("Amazon did not accept the imported session. Try signing in again.")
|
|
388
|
+
self.is_authenticated = True
|
|
389
|
+
|
|
390
|
+
with cookies_file_lock:
|
|
391
|
+
self._write_cookie_jar()
|
|
392
|
+
|
|
364
393
|
def login(self) -> None:
|
|
365
394
|
"""
|
|
366
395
|
Execute an Amazon login process. This will include the sign-in page, and may also include OTP (if 2FA is
|
|
@@ -445,9 +474,10 @@ class AmazonSession:
|
|
|
445
474
|
data = [{"name": name, "value": value, "domain": domain} for name, value in data.items()]
|
|
446
475
|
|
|
447
476
|
for cookie in data:
|
|
477
|
+
expires = cookie.get("expires")
|
|
448
478
|
self.session.cookies.set(cookie["name"], cookie["value"], domain=cookie.get("domain", ""),
|
|
449
479
|
path=cookie.get("path", "/"), secure=cookie.get("secure", False),
|
|
450
|
-
expires=
|
|
480
|
+
expires=int(expires) if expires is not None and expires >= 0 else None)
|
|
451
481
|
|
|
452
482
|
def _load_shared_cookie_jar(self) -> None:
|
|
453
483
|
"""
|
|
@@ -7,7 +7,7 @@ import os
|
|
|
7
7
|
import re
|
|
8
8
|
import sys
|
|
9
9
|
import tempfile
|
|
10
|
-
from typing import List, Union, Optional, Callable, Any
|
|
10
|
+
from typing import List, Union, Optional, Callable, Any, Mapping
|
|
11
11
|
|
|
12
12
|
from bs4 import Tag, BeautifulSoup
|
|
13
13
|
from requests import Response
|
|
@@ -115,15 +115,18 @@ def load_class(package: List[str], clazz: str) -> Union[Callable, Any]:
|
|
|
115
115
|
return getattr(constants_mod, clazz)
|
|
116
116
|
|
|
117
117
|
|
|
118
|
-
def has_display() -> bool:
|
|
118
|
+
def has_display(env: Optional[Mapping[str, str]] = None) -> bool:
|
|
119
119
|
"""
|
|
120
120
|
Check whether a browser window can be opened here, as signing in with a browser window needs. On Linux, that
|
|
121
121
|
needs a display (``DISPLAY`` or ``WAYLAND_DISPLAY``), which a server or a container usually doesn't have. Other
|
|
122
122
|
platforms always have one.
|
|
123
123
|
|
|
124
|
+
:param env: The environment to check, or ``None`` for the process environment.
|
|
124
125
|
:return: Whether there's a display.
|
|
125
126
|
"""
|
|
126
|
-
|
|
127
|
+
environment = os.environ if env is None else env
|
|
128
|
+
return not sys.platform.startswith("linux") or bool(
|
|
129
|
+
environment.get("DISPLAY") or environment.get("WAYLAND_DISPLAY"))
|
|
127
130
|
|
|
128
131
|
|
|
129
132
|
def cleanup_html_text(text: str) -> str:
|
|
@@ -175,4 +178,10 @@ def make_private_dirs(path: str) -> None:
|
|
|
175
178
|
|
|
176
179
|
:param path: The directory to create.
|
|
177
180
|
"""
|
|
178
|
-
|
|
181
|
+
missing_dirs = []
|
|
182
|
+
while path and not os.path.isdir(path):
|
|
183
|
+
missing_dirs.append(path)
|
|
184
|
+
path = os.path.dirname(path)
|
|
185
|
+
|
|
186
|
+
for directory in reversed(missing_dirs):
|
|
187
|
+
os.makedirs(directory, mode=0o700, exist_ok=True)
|
|
@@ -38,6 +38,122 @@ class TestSession(UnitTestCase):
|
|
|
38
38
|
"some-password",
|
|
39
39
|
config=self.test_config)
|
|
40
40
|
|
|
41
|
+
@responses.activate
|
|
42
|
+
def test_import_cookies_without_verification(self):
|
|
43
|
+
# GIVEN
|
|
44
|
+
self.amazon_session.session.cookies.set("old", "stale", domain=".amazon.com")
|
|
45
|
+
self.amazon_session.is_authenticated = True
|
|
46
|
+
self.amazon_session._sign_in_required = True
|
|
47
|
+
cookies = [{"name": "x-main", "value": "signed-in", "domain": ".amazon.com", "path": "/",
|
|
48
|
+
"secure": True, "expires": -1},
|
|
49
|
+
{"name": "session-id", "value": "session", "domain": "www.amazon.com", "path": "/orders",
|
|
50
|
+
"secure": True, "expires": 2000000000},
|
|
51
|
+
{"name": "foreign", "value": "ignored", "domain": ".amazon.de"},
|
|
52
|
+
{"name": "suffix", "value": "ignored", "domain": "notamazon.com"},
|
|
53
|
+
{"name": "prefix", "value": "ignored", "domain": "amazon.com.example.com"},
|
|
54
|
+
{"name": "hostless", "value": "ignored"}]
|
|
55
|
+
|
|
56
|
+
# WHEN
|
|
57
|
+
self.amazon_session.import_cookies(cookies, verify=False)
|
|
58
|
+
|
|
59
|
+
# THEN
|
|
60
|
+
self.assertEqual(0, len(responses.calls))
|
|
61
|
+
self.assertFalse(self.amazon_session.is_authenticated)
|
|
62
|
+
self.assertFalse(self.amazon_session._sign_in_required)
|
|
63
|
+
restored = AmazonSession(config=self.test_config)
|
|
64
|
+
self.assertEqual({"x-main": "signed-in", "session-id": "session"}, restored.session.cookies.get_dict())
|
|
65
|
+
attributes = {cookie.name: cookie for cookie in restored.session.cookies}
|
|
66
|
+
self.assertTrue(attributes["x-main"].secure)
|
|
67
|
+
self.assertIsNone(attributes["x-main"].expires)
|
|
68
|
+
self.assertEqual(".amazon.com", attributes["x-main"].domain)
|
|
69
|
+
self.assertEqual("/orders", attributes["session-id"].path)
|
|
70
|
+
self.assertEqual(2000000000, attributes["session-id"].expires)
|
|
71
|
+
if sys.platform != "win32":
|
|
72
|
+
self.assertEqual(0o600, os.stat(self.test_config.cookie_jar_path).st_mode & 0o777)
|
|
73
|
+
|
|
74
|
+
@responses.activate
|
|
75
|
+
def test_import_cookies_keeps_zero_expiry(self):
|
|
76
|
+
# WHEN
|
|
77
|
+
self.amazon_session.import_cookies(
|
|
78
|
+
[{"name": "expired", "value": "old", "domain": ".amazon.com", "expires": 0}], verify=False)
|
|
79
|
+
|
|
80
|
+
# THEN
|
|
81
|
+
restored = AmazonSession(config=self.test_config)
|
|
82
|
+
self.assertEqual(0, next(iter(restored.session.cookies)).expires)
|
|
83
|
+
request = restored.session.prepare_request(requests.Request("GET", self.test_config.constants.BASE_URL))
|
|
84
|
+
self.assertNotIn("expired=old", request.headers.get("Cookie", ""))
|
|
85
|
+
self.assertEqual(0, len(responses.calls))
|
|
86
|
+
|
|
87
|
+
@responses.activate
|
|
88
|
+
def test_import_cookies_verifies_by_default(self):
|
|
89
|
+
# GIVEN
|
|
90
|
+
check_response = self.given_session_check_page_exists()
|
|
91
|
+
self.amazon_session._sign_in_required = True
|
|
92
|
+
|
|
93
|
+
# WHEN
|
|
94
|
+
self.amazon_session.import_cookies([{"name": "x-main", "value": "signed-in", "domain": ".amazon.com"}])
|
|
95
|
+
|
|
96
|
+
# THEN
|
|
97
|
+
self.assertEqual(1, check_response.call_count)
|
|
98
|
+
self.assertTrue(self.amazon_session.is_authenticated)
|
|
99
|
+
self.assertFalse(self.amazon_session._sign_in_required)
|
|
100
|
+
self.assertEqual("signed-in", AmazonSession(config=self.test_config).session.cookies.get("x-main"))
|
|
101
|
+
|
|
102
|
+
@responses.activate
|
|
103
|
+
def test_import_cookies_rejects_missing_auth_cookies(self):
|
|
104
|
+
# GIVEN
|
|
105
|
+
self.amazon_session.is_authenticated = True
|
|
106
|
+
|
|
107
|
+
# WHEN
|
|
108
|
+
with self.assertRaises(AmazonAuthSignInError):
|
|
109
|
+
self.amazon_session.import_cookies([{"name": "x-main", "value": "foreign", "domain": ".amazon.de"}])
|
|
110
|
+
|
|
111
|
+
# THEN
|
|
112
|
+
self.assertFalse(self.amazon_session.is_authenticated)
|
|
113
|
+
self.assertEqual(0, len(responses.calls))
|
|
114
|
+
|
|
115
|
+
@responses.activate
|
|
116
|
+
def test_import_cookies_rejects_expired_session(self):
|
|
117
|
+
# GIVEN
|
|
118
|
+
self.given_authenticated_url_redirects_to_login()
|
|
119
|
+
self.given_login_responses_success()
|
|
120
|
+
self.amazon_session.is_authenticated = True
|
|
121
|
+
|
|
122
|
+
# WHEN
|
|
123
|
+
with self.assertRaises(AmazonAuthSignInError):
|
|
124
|
+
self.amazon_session.import_cookies([{"name": "x-main", "value": "expired", "domain": ".amazon.com"}])
|
|
125
|
+
|
|
126
|
+
# THEN
|
|
127
|
+
self.assertFalse(self.amazon_session.is_authenticated)
|
|
128
|
+
self.assertTrue(self.amazon_session._sign_in_required)
|
|
129
|
+
|
|
130
|
+
@responses.activate
|
|
131
|
+
def test_import_cookies_propagates_verification_error(self):
|
|
132
|
+
# GIVEN
|
|
133
|
+
self.given_session_check_page_exists(status=503)
|
|
134
|
+
self.amazon_session.is_authenticated = True
|
|
135
|
+
|
|
136
|
+
# WHEN
|
|
137
|
+
with self.assertRaises(AmazonAuthError):
|
|
138
|
+
self.amazon_session.import_cookies([{"name": "x-main", "value": "session", "domain": ".amazon.com"}])
|
|
139
|
+
|
|
140
|
+
# THEN
|
|
141
|
+
self.assertFalse(self.amazon_session.is_authenticated)
|
|
142
|
+
|
|
143
|
+
@responses.activate
|
|
144
|
+
def test_import_cookies_uses_configured_site(self):
|
|
145
|
+
# GIVEN
|
|
146
|
+
config = AmazonAuthConfig(data={"domain": "amazon.de"})
|
|
147
|
+
session = AmazonSession(config=config)
|
|
148
|
+
|
|
149
|
+
# WHEN
|
|
150
|
+
session.import_cookies([{"name": "x-main", "value": "de", "domain": ".amazon.de"},
|
|
151
|
+
{"name": "foreign", "value": "com", "domain": ".amazon.com"}], verify=False)
|
|
152
|
+
|
|
153
|
+
# THEN
|
|
154
|
+
self.assertEqual({"x-main": "de"}, AmazonSession(config=config).session.cookies.get_dict())
|
|
155
|
+
self.assertEqual(0, len(responses.calls))
|
|
156
|
+
|
|
41
157
|
@responses.activate
|
|
42
158
|
def test_login(self):
|
|
43
159
|
# GIVEN
|
|
@@ -99,6 +99,16 @@ class TestUtil(UnitTestCase):
|
|
|
99
99
|
# THEN
|
|
100
100
|
self.assertIsNone(tag)
|
|
101
101
|
|
|
102
|
+
@patch("amazonauth.util.sys.platform", "linux")
|
|
103
|
+
def test_has_display_supplied_environment(self):
|
|
104
|
+
# GIVEN
|
|
105
|
+
with patch.dict(os.environ, {"DISPLAY": ":1"}):
|
|
106
|
+
# WHEN / THEN
|
|
107
|
+
self.assertFalse(has_display({}))
|
|
108
|
+
self.assertTrue(has_display({"DISPLAY": ":42"}))
|
|
109
|
+
self.assertTrue(has_display({"WAYLAND_DISPLAY": "wayland-2"}))
|
|
110
|
+
self.assertTrue(has_display())
|
|
111
|
+
|
|
102
112
|
@patch.object(sys, "platform", "linux")
|
|
103
113
|
def test_has_display_linux_without_display(self):
|
|
104
114
|
# GIVEN
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|