From 4b53e7b3abb3bc3621a9dcf6f7638955b9cc5f28 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Sun, 2 Aug 2026 22:57:40 +0330 Subject: [PATCH] implement automate Ravin LMS login --- .env.example | 1 + .gitignore | 1 + CHANGELOG.md | 8 ++ CONTRIBUTING.md | 2 +- README.md | 37 ++--- SECURITY.md | 2 +- pyproject.toml | 5 +- ravin_downloader.py | 298 ++++++++++++++++++++++++++++++++++++++- test_ravin_downloader.py | 119 ++++++++++++++++ 9 files changed, 447 insertions(+), 26 deletions(-) diff --git a/.env.example b/.env.example index 5003933..fa603b5 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,6 @@ # Copy this file to .env. Never commit real values. RAVIN_USERNAME="" RAVIN_PASSWORD="" +RAVIN_LOGIN_URL="https://lms.ravinacademy.com/" RAVIN_USER_AGENT="" RAVIN_COOKIE="" diff --git a/.gitignore b/.gitignore index 983850f..d3c9b7c 100644 --- a/.gitignore +++ b/.gitignore @@ -123,6 +123,7 @@ celerybeat.pid # Environments .env +.ravin-browser-profile/ .venv env/ venv/ diff --git a/CHANGELOG.md b/CHANGELOG.md index d54d37c..db82326 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented here. +## 0.2.0 - 2026-08-02 + +- Add a persistent, interactive installed-browser login flow that handles Cloudflare normally. +- Start Ravin authentication at its account portal and automatically follow its Moodle handoff. +- Capture the launched browser's User-Agent and cookies and update `.env` automatically. +- Automatically reopen the authentication browser when a saved session expires. +- Keep manual request-header entry as an explicit fallback. + ## 0.1.0 - 2026-08-02 - List enrolled Moodle courses through the mobile API or authenticated AJAX fallback. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a954d56..7fe5ce6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ Contributions are welcome. Keep changes focused, dependency-free where practical ## Development workflow 1. Fork the repository and create a branch for the change. -2. Do not commit `.env`, browser cookies, passwords, downloaded course files, or private LMS responses. +2. Do not commit `.env`, `.ravin-browser-profile/`, browser cookies, passwords, downloaded course files, or private LMS responses. 3. Add or update tests for behavioral changes. 4. Run: diff --git a/README.md b/README.md index 23996e0..6359db6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A dependency-free command-line client that lists your enrolled Moodle courses and downloads accessible course files. It defaults to Ravin Academy, but accepts another Moodle base URL through `--site`. -The client first tries Moodle's official mobile web-service API and falls back to a normal web login plus Moodle's authenticated AJAX interface. For sites protected by Cloudflare, it can reuse request headers from a browser session. +The client first tries Moodle's official mobile web-service API and falls back to a normal web login plus Moodle's authenticated AJAX interface. For sites protected by Cloudflare, it can establish and refresh an authenticated browser session automatically. > [!IMPORTANT] > Use this tool only for courses and files your account is authorized to access. Respect the LMS terms, instructor permissions, and applicable copyright rules. This project does not bypass enrollment, DRM, or access controls. @@ -12,14 +12,14 @@ The client first tries Moodle's official mobile web-service API and falls back t - Python 3.10 or newer - An active enrollment on the target Moodle site -The runtime has no third-party Python dependencies. +The downloader itself uses only Python's standard library. Automatic browser login uses the optional Selenium package with an installed Zen, Firefox, Chrome, Chromium, or Brave browser. ## Installation After cloning or downloading the repository, install the command from its root directory: ```bash -python3 -m pip install . +python3 -m pip install '.[browser]' ``` You can then use `ravin-downloader` from any shell. Running `python3 ravin_downloader.py` directly from the repository remains supported. @@ -27,6 +27,7 @@ You can then use `ravin-downloader` from any shell. Running `python3 ravin_downl ## Quick start ```bash +ravin-downloader login ravin-downloader courses ravin-downloader files COURSE_ID ravin-downloader download COURSE_ID @@ -45,6 +46,8 @@ ravin-downloader --json files COURSE_ID On first use, missing values are requested interactively and saved in `.env` in the current directory. Copy [`.env.example`](.env.example) if you prefer to configure it manually. The file is Git-ignored and written with owner-only permissions. +`ravin-downloader login` opens an installed browser using the Git-ignored `.ravin-browser-profile/` directory. For Ravin Academy it starts at `https://lms.ravinacademy.com/`, signs in there, follows the available Moodle course-launch link, and captures the resulting session on `training.ravinacademy.com`. If `.env` already contains `RAVIN_USERNAME` and `RAVIN_PASSWORD`, a compatible login form is filled automatically. Once login succeeds, the browser closes and `.env` is updated with the exact User-Agent and cookies. Use `--browser-executable /path/to/browser` to override automatic detection. + Never commit or share `.env`. It may contain both account credentials and a temporary authenticated browser session. If the academy disables its mobile token service, the fallback is automatic. You can force that path for troubleshooting: @@ -53,43 +56,45 @@ If the academy disables its mobile token service, the fallback is automatic. You ravin-downloader --web-only --username YOUR_USERNAME courses ``` -## When Cloudflare blocks terminal login +## Browser login and Cloudflare -Ravin Academy currently puts a Cloudflare browser check in front of both Moodle login endpoints. If the normal command reports that Cloudflare requires a real browser session: - -1. Open the LMS in a normal browser and log in. -2. Open the browser's Developer Tools, select **Network**, and reload the LMS page. -3. Select the main `view.php` or `courses.php` request. -4. Under **Request Headers**, copy the complete `User-Agent` value and the complete `Cookie` value. -5. Run the browser-session mode: +Ravin Academy protects its account portal and Moodle with a browser check. Set up the browser helper once: ```bash -ravin-downloader --browser-session courses +python3 -m pip install '.[browser]' +ravin-downloader login ``` -Paste the User-Agent normally and the Cookie header into the hidden prompt. After the headers are validated, they are saved in `.env` with owner-only permissions and ignored by Git. The same file can contain all four values: +After authentication, `.env` can contain these values: ```dotenv RAVIN_USERNAME="your username" RAVIN_PASSWORD="your password" +RAVIN_LOGIN_URL="https://lms.ravinacademy.com/" RAVIN_USER_AGENT="the complete browser User-Agent" RAVIN_COOKIE="the complete browser Cookie header" ``` -Values entered at the script's prompts are written or updated automatically. Later commands reuse `.env`, so you can simply run: +Later commands reuse `.env`, so you can simply run: ```bash ravin-downloader files 44 ravin-downloader download 44 ``` -The saved session is checked on every run. When it expires or Cloudflare rejects it, the tool asks for fresh headers and replaces the saved copy. You can force that refresh yourself with: +The saved session is checked on every run. When it expires or Cloudflare rejects it, the authentication browser opens automatically and replaces the saved values. You can force that refresh yourself with: ```bash ravin-downloader --refresh-session courses ``` -Never send `.env`, your password, or its Cookie value to another person; they grant access to your LMS account or signed-in session. +If browser automation is unavailable, manual header entry remains available as a fallback: + +```bash +ravin-downloader --manual-session --refresh-session courses +``` + +Never send `.env`, `.ravin-browser-profile/`, your password, or its Cookie value to another person; they grant access to your LMS account or signed-in session. ## Development diff --git a/SECURITY.md b/SECURITY.md index b444a99..b77be6c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,6 +8,6 @@ Include the affected version, a minimal reproduction using synthetic data, and t ## Credential handling -The downloader may store `RAVIN_USERNAME`, `RAVIN_PASSWORD`, `RAVIN_USER_AGENT`, and `RAVIN_COOKIE` in a local `.env` file. That file is excluded from Git and created with owner-only permissions, but users are still responsible for protecting it. Browser cookies should be treated like passwords and refreshed if exposed. +The downloader may store `RAVIN_USERNAME`, `RAVIN_PASSWORD`, `RAVIN_USER_AGENT`, and `RAVIN_COOKIE` in a local `.env` file. Automatic login also stores a dedicated browser profile in `.ravin-browser-profile/`. Both paths are excluded from Git, and `.env` is created with owner-only permissions, but users are still responsible for protecting them. Browser cookies should be treated like passwords and refreshed if exposed. Only download content your account is authorized to access. This project does not support bypassing authentication, enrollment, DRM, or other access controls. diff --git a/pyproject.toml b/pyproject.toml index 9f0373e..c3fd6f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ravin-moodle-downloader" -version = "0.1.0" +version = "0.2.0" description = "List and download authorized course files from Ravin Academy or another Moodle site" readme = "README.md" requires-python = ">=3.10" @@ -26,6 +26,9 @@ classifiers = [ ] dependencies = [] +[project.optional-dependencies] +browser = ["selenium>=4.46,<5"] + [project.scripts] ravin-downloader = "ravin_downloader:main" diff --git a/ravin_downloader.py b/ravin_downloader.py index e07d7d5..4ebae97 100644 --- a/ravin_downloader.py +++ b/ravin_downloader.py @@ -19,6 +19,7 @@ import json import mimetypes import os import re +import shutil import sys import tempfile import time @@ -32,13 +33,15 @@ from typing import Any, Iterable DEFAULT_SITE = "https://training.ravinacademy.com" -__version__ = "0.1.0" +DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/" +__version__ = "0.2.0" USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)" DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} DEFAULT_ENV_FILE = Path.cwd() / ".env" ENV_KEYS = { "username": "RAVIN_USERNAME", "password": "RAVIN_PASSWORD", + "login_url": "RAVIN_LOGIN_URL", "user_agent": "RAVIN_USER_AGENT", "cookie": "RAVIN_COOKIE", } @@ -845,12 +848,253 @@ def _prompt_browser_session(args: argparse.Namespace, *, fresh: bool = False) -> return user_agent, cookie_header +def _find_browser_executable(explicit: Path | None = None) -> Path | None: + if explicit: + candidate = explicit.expanduser().resolve() + return candidate if candidate.is_file() else None + candidates = [ + Path("/Applications/Zen.app/Contents/MacOS/zen"), + Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"), + Path("/Applications/Chromium.app/Contents/MacOS/Chromium"), + Path("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"), + Path("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"), + Path("/Applications/Firefox.app/Contents/MacOS/firefox"), + ] + for command in ("zen", "firefox", "google-chrome", "chromium", "chromium-browser", "brave-browser"): + found = shutil.which(command) + if found: + candidates.append(Path(found)) + return next((candidate for candidate in candidates if candidate.is_file()), None) + + +def _browser_login_url(args: argparse.Namespace) -> str: + configured = getattr(args, "login_url", None) or _env_value(args, ENV_KEYS["login_url"]) + if configured: + return configured + hostname = (urllib.parse.urlsplit(args.site).hostname or "").casefold() + if hostname == "training.ravinacademy.com": + return DEFAULT_RAVIN_LOGIN_URL + return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php") + + +def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: + """Open an installed browser through Selenium and capture its authenticated session.""" + try: + from selenium import webdriver + from selenium.common.exceptions import WebDriverException + from selenium.webdriver.common.by import By + except ImportError as exc: + raise MoodleError( + "automatic browser login is not installed. Run:\n" + " python3 -m pip install 'ravin-moodle-downloader[browser]'" + ) from exc + + executable = _find_browser_executable(args.browser_executable) + if executable is None: + raise MoodleError( + "no supported browser was found. Install Firefox/Zen/Chrome, or pass " + "--browser-executable /path/to/browser" + ) + + profile = args.browser_profile.expanduser().resolve() + profile.mkdir(parents=True, exist_ok=True, mode=0o700) + try: + os.chmod(profile, 0o700) + except OSError: + pass + + browser_name = executable.name.casefold() + try: + if "firefox" in browser_name or "zen" in browser_name: + from selenium.webdriver.firefox.options import Options + from selenium.webdriver.firefox.service import Service + + options = Options() + options.binary_location = str(executable) + options.add_argument("-profile") + options.add_argument(str(profile)) + driver_path = shutil.which("geckodriver") + service = Service(executable_path=driver_path) if driver_path else Service() + driver = webdriver.Firefox(options=options, service=service) + else: + from selenium.webdriver.chrome.options import Options + + options = Options() + options.binary_location = str(executable) + options.add_argument(f"--user-data-dir={profile}") + options.add_argument("--no-first-run") + driver = webdriver.Chrome(options=options) + except WebDriverException as exc: + raise MoodleError( + f"could not launch {executable.name}: {exc}. " + "Selenium Manager may need network access once to install the matching driver." + ) from exc + + login_url = _browser_login_url(args) + username = _env_value(args, ENV_KEYS["username"]) + password = _env_value(args, ENV_KEYS["password"]) + deadline = time.monotonic() + max(args.login_timeout, 30) + print(f"Opening {executable.name} for LMS authentication...", file=sys.stderr) + print("Complete Cloudflare or LMS login in that window if requested.", file=sys.stderr) + try: + driver.get(login_url) + submitted_credentials = False + credential_attempts = 0 + last_location = "" + while time.monotonic() < deadline: + current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl() + if current_location != last_location: + print(f"Browser is at {current_location}", file=sys.stderr) + last_location = current_location + try: + logged_in = bool( + driver.execute_script( + """return Boolean( + window.M && M.cfg && Number(M.cfg.userId) > 0 && + document.querySelector('a[href*="/login/logout.php"]') + );""" + ) + ) + except WebDriverException: + logged_in = False + if logged_in: + cookies = driver.get_cookies() + user_agent = str(driver.execute_script("return navigator.userAgent;")) + cookie_header = "; ".join( + f"{cookie['name']}={cookie['value']}" + for cookie in cookies + if cookie.get("name") and cookie.get("value") + ) + if not cookie_header: + raise MoodleError("browser login succeeded, but no site cookies were available") + return user_agent, cookie_header + + # Ravin's account portal owns the login. Its Moodle launch link creates + # the session on training.ravinacademy.com and redirects there. + launch_links = driver.find_elements( + By.CSS_SELECTOR, + 'a[href*="/moodle/login_student_user/"]', + ) + launch_urls = [ + element.get_attribute("href") + for element in launch_links + if element.is_displayed() and element.get_attribute("href") + ] + if launch_urls: + print("LMS login accepted; opening the Moodle course portal.", file=sys.stderr) + driver.get(launch_urls[0]) + submitted_credentials = False + continue + + if submitted_credentials: + error_elements = driver.find_elements( + By.CSS_SELECTOR, + ".loginerrors, .alert-danger, .invalid-feedback, " + ".field-validation-error, .error-message, .toast-error, " + ".swal2-validation-message, [data-region=\"login-error\"], [role=\"alert\"]", + ) + error_messages = [ + " ".join(element.text.split()) + for element in error_elements + if element.is_displayed() and element.text.strip() + ] + if error_messages: + if credential_attempts >= 3: + raise MoodleError(f"the LMS rejected the login: {error_messages[0][:300]}") + print(f"The LMS rejected the saved login: {error_messages[0][:300]}", file=sys.stderr) + print("Enter fresh credentials in this terminal.", file=sys.stderr) + username, password = _credentials(args, fresh=True) + _save_env_values( + args.env_file, + { + ENV_KEYS["username"]: username, + ENV_KEYS["password"]: password, + }, + ) + args.env_values.update( + { + ENV_KEYS["username"]: username, + ENV_KEYS["password"]: password, + } + ) + submitted_credentials = False + + if username and password and not submitted_credentials: + login_controls = driver.execute_script( + """const visible = (element) => { + const style = window.getComputedStyle(element); + const box = element.getBoundingClientRect(); + return !element.disabled && style.display !== 'none' && + style.visibility !== 'hidden' && box.width > 0 && box.height > 0; + }; + const passwords = [...document.querySelectorAll('input[type="password"]')] + .filter(visible); + if (passwords.length !== 1) return null; + const password = passwords[0]; + const form = password.form || password.closest('form'); + if (!form) return null; + const candidates = [...form.querySelectorAll('input')].filter((element) => { + const type = (element.type || 'text').toLowerCase(); + return visible(element) && ![ + 'password', 'hidden', 'submit', 'button', 'checkbox', + 'radio', 'file', 'reset' + ].includes(type); + }); + const preferred = /user|mobile|phone|email|login|national/i; + const username = candidates.find((element) => preferred.test( + `${element.name} ${element.id} ${element.autocomplete}` + )) || candidates[0]; + const submits = [...form.querySelectorAll('button, input[type="submit"]')] + .filter((element) => visible(element) && element.type === 'submit'); + return username && submits.length ? [username, password, submits[0]] : null;""" + ) + if login_controls: + username_input, password_input, submit_button = login_controls + driver.execute_script( + """const setValue = (element, value) => { + const setter = Object.getOwnPropertyDescriptor( + HTMLInputElement.prototype, 'value' + ).set; + setter.call(element, value); + element.dispatchEvent(new Event('input', {bubbles: true})); + element.dispatchEvent(new Event('change', {bubbles: true})); + }; + setValue(arguments[0], arguments[1]); + setValue(arguments[2], arguments[3]); + const form = arguments[0].closest('form'); + if (form && form.requestSubmit) { + form.requestSubmit(arguments[4]); + } else { + arguments[4].click(); + }""", + username_input, + username, + password_input, + password, + submit_button, + ) + submitted_credentials = True + credential_attempts += 1 + print("Submitted the stored LMS credentials.", file=sys.stderr) + time.sleep(1) + raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds") + except WebDriverException as exc: + raise MoodleError(f"browser authentication failed: {exc}") from exc + finally: + driver.quit() + + def _authenticate_browser_session( args: argparse.Namespace, saved: tuple[str, str] | None = None, ) -> tuple[MoodleClient, str]: from_saved = saved is not None and not args.refresh_session - user_agent, cookie_header = saved if from_saved else _prompt_browser_session(args) + if from_saved: + user_agent, cookie_header = saved + elif args.manual_session: + user_agent, cookie_header = _prompt_browser_session(args, fresh=True) + else: + user_agent, cookie_header = _capture_browser_session(args) client = MoodleClient( args.site, cookie_header=cookie_header, @@ -862,8 +1106,12 @@ def _authenticate_browser_session( if not from_saved: raise print(f"Saved browser session is no longer valid ({exc}).", file=sys.stderr) - print("Please paste fresh headers from a logged-in browser request.", file=sys.stderr) - user_agent, cookie_header = _prompt_browser_session(args, fresh=True) + if args.manual_session: + print("Please paste fresh headers from a logged-in browser request.", file=sys.stderr) + user_agent, cookie_header = _prompt_browser_session(args, fresh=True) + else: + print("Opening the authentication browser to refresh it.", file=sys.stderr) + user_agent, cookie_header = _capture_browser_session(args) client = MoodleClient( args.site, cookie_header=cookie_header, @@ -873,12 +1121,14 @@ def _authenticate_browser_session( _save_env_values( args.env_file, { + ENV_KEYS["login_url"]: _browser_login_url(args), ENV_KEYS["user_agent"]: user_agent, ENV_KEYS["cookie"]: cookie_header, }, ) args.env_values.update( { + ENV_KEYS["login_url"]: _browser_login_url(args), ENV_KEYS["user_agent"]: user_agent, ENV_KEYS["cookie"]: cookie_header, } @@ -902,12 +1152,19 @@ def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.") parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})") + parser.add_argument( + "--login-url", + help=( + "account portal used for browser login; defaults to " + f"{DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy" + ), + ) parser.add_argument("--username", help="LMS username; password is prompted securely") parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a normal web session") parser.add_argument( "--browser-session", action="store_true", - help="reuse request headers from an already logged-in browser (works with Cloudflare)", + help="force saved or automatic browser-session authentication", ) parser.add_argument( "--browser-user-agent", @@ -922,11 +1179,34 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument( "--refresh-session", action="store_true", - help="ignore the saved browser session and ask for fresh headers", + help="ignore the saved browser session and open the authentication browser", + ) + parser.add_argument( + "--manual-session", + action="store_true", + help="prompt for User-Agent and Cookie headers instead of opening a browser", + ) + parser.add_argument( + "--browser-profile", + type=Path, + default=Path.cwd() / ".ravin-browser-profile", + help="persistent profile for automatic browser login", + ) + parser.add_argument( + "--browser-executable", + type=Path, + help="installed Zen, Firefox, Chrome, Chromium, or Brave executable", + ) + parser.add_argument( + "--login-timeout", + type=int, + default=600, + help="seconds to wait for interactive browser login (default: 600)", ) parser.add_argument("--json", action="store_true", help="print machine-readable JSON") subparsers = parser.add_subparsers(dest="command", required=True) + subparsers.add_parser("login", help="open a browser and refresh the saved LMS session") subparsers.add_parser("courses", help="list enrolled courses") files_parser = subparsers.add_parser("files", help="list downloadable files in a course") files_parser.add_argument("course_id", type=int) @@ -943,6 +1223,10 @@ def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) try: args.env_values = _load_env_file(args.env_file) + if args.command == "login": + client, mode = _authenticate_browser_session(args) + print(f"Authenticated using {mode}; updated {args.env_file}.") + return 0 saved_session = _browser_session_values(args, fresh=args.refresh_session) if args.browser_session or args.refresh_session or saved_session is not None: client, mode = _authenticate_browser_session(args, saved_session) @@ -967,7 +1251,7 @@ def main(argv: list[str] | None = None) -> int: except MoodleError as exc: if "cloudflare requires a real browser session" not in str(exc).casefold(): raise - print("Cloudflare blocked password login; switching to a saved browser session.", file=sys.stderr) + print("Cloudflare blocked password login; opening the authentication browser.", file=sys.stderr) client, mode = _authenticate_browser_session(args) print(f"Authenticated using {mode}.", file=sys.stderr) diff --git a/test_ravin_downloader.py b/test_ravin_downloader.py index 5be9654..3769b44 100644 --- a/test_ravin_downloader.py +++ b/test_ravin_downloader.py @@ -1,9 +1,13 @@ import email.message import http.client import os +import sys import tempfile +import types import unittest from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch from ravin_downloader import ( FileItem, @@ -11,12 +15,15 @@ from ravin_downloader import ( _FormParser, _LinkParser, _clean_name, + _browser_login_url, + _capture_browser_session, _filename_from_headers, _is_cloudflare_challenge, _load_env_file, _parse_moodle_config, _save_env_values, _unique, + build_parser, ) @@ -62,6 +69,118 @@ class _FakeDownloadClient(MoodleClient): class ParserTests(unittest.TestCase): + def test_login_command_parses_without_course_id(self): + args = build_parser().parse_args(["login"]) + self.assertEqual(args.command, "login") + self.assertFalse(args.manual_session) + + def test_browser_login_captures_user_agent_and_cookies(self): + class FakeLaunchLink: + def is_displayed(self): + return True + + def get_attribute(self, name): + if name == "href": + return "https://lms.example/moodle/login_student_user/162/" + return None + + class FakeDriver: + current_url = "about:blank" + + def get(self, url): + if "/moodle/login_student_user/" in url: + self.current_url = "https://training.example/my/" + else: + self.current_url = url + + def execute_script(self, expression): + if "navigator.userAgent" in expression: + return "Synthetic Browser/1" + return self.current_url == "https://training.example/my/" + + def find_elements(self, _by, selector): + if "login_student_user" in selector and self.current_url == "https://lms.example/": + return [FakeLaunchLink()] + return [] + + def get_cookies(self): + return [ + {"name": "MoodleSession", "value": "synthetic"}, + {"name": "cf_clearance", "value": "synthetic"}, + ] + + def quit(self): + return None + + class FakeOptions: + binary_location = "" + + def add_argument(self, _argument): + return None + + class FakeService: + def __init__(self, **_kwargs): + return None + + fake_webdriver = SimpleNamespace( + Firefox=lambda **_kwargs: FakeDriver(), + Chrome=lambda **_kwargs: FakeDriver(), + ) + fake_selenium = types.ModuleType("selenium") + fake_selenium.webdriver = fake_webdriver + fake_common = types.ModuleType("selenium.common") + fake_exceptions = types.ModuleType("selenium.common.exceptions") + fake_exceptions.WebDriverException = RuntimeError + fake_webdriver_module = types.ModuleType("selenium.webdriver") + fake_webdriver_common = types.ModuleType("selenium.webdriver.common") + fake_by = types.ModuleType("selenium.webdriver.common.by") + fake_by.By = SimpleNamespace(CSS_SELECTOR="css selector") + fake_firefox = types.ModuleType("selenium.webdriver.firefox") + fake_firefox_options = types.ModuleType("selenium.webdriver.firefox.options") + fake_firefox_options.Options = FakeOptions + fake_firefox_service = types.ModuleType("selenium.webdriver.firefox.service") + fake_firefox_service.Service = FakeService + + with tempfile.TemporaryDirectory() as directory: + executable = Path(directory) / "zen" + executable.touch() + args = SimpleNamespace( + site="https://training.example", + login_url="https://lms.example/", + browser_profile=Path(directory) / "profile", + browser_executable=executable, + login_timeout=30, + env_values={}, + ) + with patch.dict( + sys.modules, + { + "selenium": fake_selenium, + "selenium.common": fake_common, + "selenium.common.exceptions": fake_exceptions, + "selenium.webdriver": fake_webdriver_module, + "selenium.webdriver.common": fake_webdriver_common, + "selenium.webdriver.common.by": fake_by, + "selenium.webdriver.firefox": fake_firefox, + "selenium.webdriver.firefox.options": fake_firefox_options, + "selenium.webdriver.firefox.service": fake_firefox_service, + }, + ): + user_agent, cookie_header = _capture_browser_session(args) + self.assertEqual(user_agent, "Synthetic Browser/1") + self.assertEqual( + cookie_header, + "MoodleSession=synthetic; cf_clearance=synthetic", + ) + + def test_ravin_browser_login_starts_at_account_portal(self): + args = SimpleNamespace( + site="https://training.ravinacademy.com", + login_url=None, + env_values={}, + ) + self.assertEqual(_browser_login_url(args), "https://lms.ravinacademy.com/") + def test_parses_login_form_and_hidden_token(self): parser = _FormParser() parser.feed(