Download tasks/ioby/tests/oracle-runtime/clone/app.py from TIGER-Lab/WebsiteBench: direct link, hf CLI and curl.
- Browser
- Download file 33.4 kB
-
https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/ioby/tests/oracle-runtime/clone/app.py
- Command line
-
hf download hf://datasets/TIGER-Lab/WebsiteBench/tasks/ioby/tests/oracle-runtime/clone/app.py
-
curl -L -o app.py https://huggingface.co/datasets/TIGER-Lab/WebsiteBench/resolve/main/tasks/ioby/tests/oracle-runtime/clone/app.py
33.4 kB
| """ioby WebsiteBench offline clone. | |
| Public pages follow anonymous archival captures from 2026-08-24. Donation, | |
| account, recovery, favorite, and recurring-plan behavior is an explicit local | |
| simulation because the observed source was closed and exposed no usable live | |
| transaction flow. Runtime requests are same-origin and never leave the clone. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| import sys | |
| from pathlib import Path | |
| from typing import Any | |
| from urllib.parse import urlsplit | |
| from fastapi import FastAPI, Request | |
| from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response | |
| from fastapi.staticfiles import StaticFiles | |
| ROOT = Path(__file__).resolve().parent | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from backend import business # noqa: E402 | |
| from backend.site_backend_integration import open_site_services # noqa: E402 | |
| import views # noqa: E402 | |
| from websitebench.local_clone_auth import AuthConflict, AuthError, AuthRateLimited # noqa: E402 | |
| from websitebench.site_backend import PaymentError, PaymentRejected # noqa: E402 | |
| SITE_ID = "ioby" | |
| PROJECT_SLUG = "make-block-bloom" | |
| BACKEND, AUTH = open_site_services() | |
| with BACKEND.lifecycle.connection(transaction=True) as connection: | |
| business.migrate(connection) | |
| DEMO_ACCOUNT_ID = AUTH.seed_account( | |
| subject_id="ioby-demo-neighbor", | |
| email="demo@ioby.local", | |
| display_name="Morgan Neighbor", | |
| password="Neighbor123!", | |
| ) | |
| with BACKEND.lifecycle.connection(transaction=True) as connection: | |
| business.seed_demo(connection, DEMO_ACCOUNT_ID) | |
| APP = FastAPI(title="ioby offline clone", docs_url=None, redoc_url=None, openapi_url=None) | |
| app = APP | |
| APP.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") | |
| DEPLOYED_COOKIE = str(BACKEND.session_cookie["name"]) | |
| LOCAL_COOKIE = "websitebench-ioby-session" | |
| CSP = ( | |
| "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; " | |
| "connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'" | |
| ) | |
| EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") | |
| def _loopback(request: Request) -> bool: | |
| return (request.url.hostname or "").casefold() in { | |
| "127.0.0.1", | |
| "localhost", | |
| "::1", | |
| "[::1]", | |
| "testserver", | |
| } | |
| def _cookie_name(request: Request) -> str: | |
| return LOCAL_COOKIE if _loopback(request) else DEPLOYED_COOKIE | |
| def _origin(value: str) -> tuple[str, str, int]: | |
| parsed = urlsplit(value) | |
| return ( | |
| parsed.scheme.casefold(), | |
| (parsed.hostname or "").casefold(), | |
| parsed.port or (443 if parsed.scheme.casefold() == "https" else 80), | |
| ) | |
| def _request_origin(request: Request) -> tuple[str, str, int]: | |
| return ( | |
| request.url.scheme.casefold(), | |
| (request.url.hostname or "").casefold(), | |
| request.url.port or (443 if request.url.scheme.casefold() == "https" else 80), | |
| ) | |
| def _set_cookie(request: Request, response: Response, token: str) -> None: | |
| response.set_cookie( | |
| _cookie_name(request), | |
| token, | |
| secure=not _loopback(request), | |
| httponly=True, | |
| samesite="lax", | |
| path="/", | |
| ) | |
| async def runtime_boundary(request: Request, call_next): | |
| if request.method in {"POST", "PUT", "PATCH", "DELETE"}: | |
| source = request.headers.get("origin") or request.headers.get("referer") | |
| invalid = source == "null" and not _loopback(request) | |
| if source and source != "null": | |
| invalid = _origin(source) != _request_origin(request) | |
| elif not source: | |
| invalid = not _loopback(request) | |
| if invalid: | |
| return JSONResponse( | |
| {"error": "cross-origin state changes are not allowed"}, status_code=403 | |
| ) | |
| supplied = request.cookies.get(_cookie_name(request)) | |
| token, session = AUTH.ensure_session(supplied) | |
| request.state.auth_token = token | |
| request.state.auth_info = session | |
| response = await call_next(request) | |
| if request.url.path.startswith("/static/assets/") and request.url.path.endswith(".svg"): | |
| # Captured first-party SVGs contain their own presentation rules. The | |
| # narrowly scoped image response may apply those rules; HTML documents | |
| # retain the strict no-inline policy above. | |
| response.headers["Content-Security-Policy"] = ( | |
| "default-src 'none'; style-src 'unsafe-inline'; sandbox" | |
| ) | |
| else: | |
| response.headers["Content-Security-Policy"] = CSP | |
| response.headers["Referrer-Policy"] = "no-referrer" | |
| response.headers["X-Content-Type-Options"] = "nosniff" | |
| response.headers["X-Frame-Options"] = "DENY" | |
| current = str(getattr(request.state, "auth_token", token)) | |
| if current != supplied: | |
| _set_cookie(request, response, current) | |
| return response | |
| def html(markup: str, status: int = 200) -> HTMLResponse: | |
| return HTMLResponse(markup, status_code=status) | |
| def see_other(path: str) -> RedirectResponse: | |
| return RedirectResponse(path, status_code=303) | |
| def db(): | |
| return BACKEND.lifecycle.connection(transaction=True) | |
| def account_of(request: Request) -> dict[str, Any] | None: | |
| session = getattr(request.state, "auth_info", {}) or {} | |
| if not session.get("authenticated"): | |
| return None | |
| return dict(session.get("account") or {}) | |
| def account_id_of(request: Request) -> str | None: | |
| account = account_of(request) | |
| return str(account["account_id"]) if account else None | |
| def owner_key_of(request: Request) -> str: | |
| return f"session:{AUTH.session_owner_digest(str(request.state.auth_token))}" | |
| def safe_next(value: Any) -> str: | |
| target = str(value or "/account") | |
| return target if target.startswith("/") and not target.startswith("//") else "/account" | |
| def unexpected_fields(form: Any, allowed: set[str]) -> bool: | |
| """Fail closed when a mutation receives client-controlled fields it does not own.""" | |
| return any(str(key) not in allowed for key in form.keys()) | |
| def _owned_donation(request: Request, donation_id: str) -> dict[str, Any] | None: | |
| with db() as connection: | |
| return business.get_donation( | |
| connection, | |
| donation_id, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| ) | |
| def favicon() -> Response: | |
| """The source links `/favicon.ico`; serve the captured ioby mark there so no page logs a 404.""" | |
| icon = ROOT / "static" / "assets" / "ioby-logo.svg" | |
| return Response(icon.read_bytes(), media_type="image/svg+xml", | |
| headers={"Cache-Control": "public, max-age=86400"}) | |
| def websitebench_health() -> dict[str, str]: | |
| return {"status": "ok"} | |
| def healthz() -> dict[str, object]: | |
| return {"ok": True, "site_id": SITE_ID, "status": "ok"} | |
| # Public source-grounded pages ------------------------------------------------- | |
| def home(request: Request): | |
| return html(views.home(account_of(request))) | |
| def project_catalog(request: Request, q: str = "", state: str = "", impact: str = ""): | |
| return html( | |
| views.project_catalog( | |
| query=q, state=state, impact=impact, account=account_of(request) | |
| ) | |
| ) | |
| def new_york(request: Request): | |
| return html(views.new_york(account_of(request))) | |
| def make_block_bloom(request: Request, notice: str = ""): | |
| account = account_of(request) | |
| saved = False | |
| if account: | |
| with db() as connection: | |
| saved = business.is_favorite( | |
| connection, str(account["account_id"]), PROJECT_SLUG | |
| ) | |
| return html(views.project_detail(account, saved=saved, notice=notice)) | |
| def favorite_get(request: Request): | |
| """The favorite control posts here; a direct GET returns to the project.""" | |
| return see_other("/project/make-block-bloom/") | |
| async def favorite(request: Request): | |
| account = account_of(request) | |
| if account is None: | |
| return see_other("/login?next=/project/make-block-bloom/") | |
| form = await request.form() | |
| if unexpected_fields(form, {"saved"}): | |
| return html(views.not_found(account), 400) | |
| target = str(form.get("saved") or "") | |
| if target not in {"0", "1"}: | |
| return html(views.not_found(account), 400) | |
| with db() as connection: | |
| saved = business.set_favorite( | |
| connection, | |
| str(account["account_id"]), | |
| PROJECT_SLUG, | |
| saved=target == "1", | |
| ) | |
| notice = "Project saved to your local account" if saved else "Project removed from saved items" | |
| return see_other(f"/project/make-block-bloom/?notice={notice.replace(' ', '+')}") | |
| SIMPLE_PROJECTS = { | |
| "crystal-gardens-immersive-healing-art-exhibition": "The Crystal Gardens: An Immersive Healing Art Exhibition", | |
| "10th-street-neighborhood-resource-center": "10th Street Neighborhood Resource Center", | |
| "sweet-sassy-girls-lemonade-stand": "Sweet & Sassy Girls - Lemonade Stand", | |
| } | |
| def other_project(request: Request, slug: str): | |
| title = SIMPLE_PROJECTS.get(slug) | |
| if title is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.simple_project(title, account_of(request))) | |
| def resources(request: Request): | |
| return html(views.resources(account_of(request))) | |
| def places(request: Request): | |
| return html(views.places(account_of(request))) | |
| def match_programs(request: Request): | |
| return html(views.match_programs(account_of(request))) | |
| def how_it_worked(request: Request): | |
| return html(views.how_it_worked(account_of(request))) | |
| def about(request: Request): | |
| return html(views.about(account_of(request))) | |
| def closing(request: Request): | |
| return html( | |
| views.generic_page( | |
| "ioby has closed", "ioby has closed its doors", "The public source is an archival site. This offline clone preserves observed pages and labels all new local simulations truthfully.", account_of(request) | |
| ) | |
| ) | |
| def terms(request: Request): | |
| return html( | |
| views.generic_page( | |
| "Local terms", "Offline clone terms", "Accounts and donations created here are local test records only. No production service is contacted.", account_of(request) | |
| ) | |
| ) | |
| REFERENCE_TITLES = { | |
| "match": { | |
| "2020-cuyahoga-arts-culture": "2020 Cuyahoga Arts & Culture Match Fund", | |
| "2020-doors-open-pittsburgh": "2020 Doors Open Pittsburgh Match Challenge", | |
| "2020-healthy-neighborhoods": "2020 Healthy Neighborhoods Challenge", | |
| "2021-con-edison-power-up": "2021 Con Edison Power Up Neighborhood Match", | |
| "2021-cuyahoga-arts-culture": "2021 Cuyahoga Arts & Culture Match Fund", | |
| "2021-detroit": "2021 Detroit Match Program", | |
| }, | |
| "places": { | |
| "arkansas": "Arkansas", | |
| "cleveland": "Cleveland", | |
| "detroit": "Detroit", | |
| "pittsburgh": "Pittsburgh", | |
| }, | |
| "how-it-works": { | |
| "currently-crowdfunding": "Currently Crowdfunding? Your questions answered here", | |
| "fees": "Fees", | |
| "criteria": "Criteria", | |
| "fiscal-sponsorship": "Fiscal Sponsorship", | |
| "match-funding": "Match Funding", | |
| "coaching": "Coaching", | |
| }, | |
| "resources": { | |
| "making-it-rain": "Making It Rain", | |
| "recipes-for-change": "Recipes For Change", | |
| "leader-toolkit": "Leader Toolkit", | |
| "report-from-the-field-the-northwest-arkansas-neighborhood-match-program": "Report from The Field: The Northwest Arkansas Neighborhood Match Program", | |
| "10-climate-conscious-projects-we-love": "10 Climate-Conscious Projects We Love", | |
| "iobys-comprehensive-guide-to-end-of-year-fundraising": "ioby’s Comprehensive Guide to End-of-Year Fundraising", | |
| "active-transit-toolkit": "Active Transit Toolkit", | |
| "sustaining-justice-in-our-neighborhoods-block-by-block": "Sustaining Justice in our Neighborhoods, Block by Block", | |
| }, | |
| "about": { | |
| "reports": "Reports", | |
| "transparency": "Transparency", | |
| "privacy": "Privacy Policy", | |
| }, | |
| } | |
| # Donation journey ------------------------------------------------------------- | |
| def donation_start(request: Request, project_slug: str): | |
| if project_slug != PROJECT_SLUG: | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.donation_amount(account_of(request))) | |
| async def donation_start_post(request: Request, project_slug: str): | |
| if project_slug != PROJECT_SLUG: | |
| return html(views.not_found(account_of(request)), 404) | |
| form = await request.form() | |
| if unexpected_fields(form, {"amount", "cadence"}): | |
| return html( | |
| views.donation_amount( | |
| account_of(request), | |
| error="This donation step received an unsupported field.", | |
| ), | |
| 400, | |
| ) | |
| raw_amount = str(form.get("amount") or "").strip() | |
| cadence = str(form.get("cadence") or "") | |
| values = {"amount": raw_amount, "cadence": cadence} | |
| try: | |
| amount_cents = int(round(float(raw_amount) * 100)) | |
| except (TypeError, ValueError): | |
| amount_cents = 0 | |
| if amount_cents < 100 or amount_cents > 10_000_000: | |
| return html( | |
| views.donation_amount( | |
| account_of(request), error="Enter an amount from $1.00 to $100,000.00.", values=values | |
| ), | |
| 400, | |
| ) | |
| if cadence not in {"one-time", "monthly"}: | |
| return html( | |
| views.donation_amount( | |
| account_of(request), error="Choose one-time or monthly.", values=values | |
| ), | |
| 400, | |
| ) | |
| with db() as connection: | |
| donation = business.create_draft( | |
| connection, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| project_slug=project_slug, | |
| amount_cents=amount_cents, | |
| cadence=cadence, | |
| ) | |
| return see_other(f"/donate/{project_slug}/details?donation_id={donation['id']}") | |
| def donation_details(request: Request, project_slug: str, donation_id: str = ""): | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.donation_details(donation, account_of(request))) | |
| async def donation_details_post(request: Request, project_slug: str, donation_id: str = ""): | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| form = await request.form() | |
| if unexpected_fields( | |
| form, {"donor_name", "donor_email", "recognition", "dedication"} | |
| ): | |
| return html( | |
| views.donation_details( | |
| donation, | |
| account_of(request), | |
| error="This donation step received an unsupported field.", | |
| ), | |
| 400, | |
| ) | |
| values = { | |
| "donor_name": " ".join(str(form.get("donor_name") or "").split()), | |
| "donor_email": str(form.get("donor_email") or "").strip().casefold(), | |
| "recognition": str(form.get("recognition") or ""), | |
| "dedication": str(form.get("dedication") or "").strip(), | |
| "tip_cents": 0, | |
| } | |
| errors: list[str] = [] | |
| if not 1 <= len(values["donor_name"]) <= 120: | |
| errors.append("Enter your full name.") | |
| if EMAIL_RE.fullmatch(values["donor_email"]) is None: | |
| errors.append("Enter a valid email for the local receipt.") | |
| if values["recognition"] not in {"public", "anonymous"}: | |
| errors.append("Choose a recognition preference.") | |
| if len(values["dedication"]) > 280: | |
| errors.append("Keep the dedication to 280 characters.") | |
| if errors: | |
| return html( | |
| views.donation_details( | |
| donation, account_of(request), error=" ".join(errors), values=values | |
| ), | |
| 400, | |
| ) | |
| with db() as connection: | |
| updated = business.update_details( | |
| connection, | |
| donation_id, | |
| values, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| ) | |
| if updated is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| return see_other(f"/donate/{project_slug}/payment?donation_id={donation_id}") | |
| def donation_payment(request: Request, project_slug: str, donation_id: str = ""): | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.donation_payment(donation, account_of(request))) | |
| async def donation_payment_post(request: Request, project_slug: str, donation_id: str = ""): | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| form = await request.form() | |
| if unexpected_fields(form, {"scenario_id"}): | |
| return html( | |
| views.donation_payment( | |
| donation, | |
| account_of(request), | |
| error="Payment credentials and server-owned checkout fields are not accepted.", | |
| ), | |
| 400, | |
| ) | |
| scenario = str(form.get("scenario_id") or "") | |
| if scenario not in {"sandbox-approved", "sandbox-declined", "sandbox-retry"}: | |
| return html( | |
| views.donation_payment( | |
| donation, account_of(request), error="Choose one local sandbox outcome." | |
| ), | |
| 400, | |
| ) | |
| try: | |
| with db() as connection: | |
| current = business.get_donation( | |
| connection, | |
| donation_id, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| ) | |
| if current is None or not current.get("donor_email"): | |
| return see_other( | |
| f"/donate/{project_slug}/details?donation_id={donation_id}" | |
| ) | |
| facts = business.payment_facts(current) | |
| flow = BACKEND.payments.create_intent( | |
| owner=facts["owner"], | |
| amount_minor=facts["amount_minor"], | |
| currency=facts["currency"], | |
| fingerprint=facts["fingerprint"], | |
| idempotency_key=f"ioby.create:{donation_id}", | |
| connection=connection, | |
| ) | |
| attempt = BACKEND.payments.attempt( | |
| flow_id=flow["flow_id"], | |
| owner=facts["owner"], | |
| amount_minor=facts["amount_minor"], | |
| currency=facts["currency"], | |
| fingerprint=facts["fingerprint"], | |
| scenario_id=scenario, | |
| idempotency_key=f"ioby.attempt:{donation_id}:{scenario}", | |
| connection=connection, | |
| ) | |
| if attempt["status"] != "APPROVED": | |
| label = "declined" if attempt["status"] == "DECLINED" else "temporarily unavailable" | |
| return html( | |
| views.donation_payment( | |
| current, | |
| account_of(request), | |
| error=f"The local sandbox result was {label}. No donation was created; choose a fresh outcome and retry.", | |
| ), | |
| 400, | |
| ) | |
| business.record_payment_approval( | |
| connection, | |
| donation_id, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| payment_flow_id=str(flow["flow_id"]), | |
| payment_attempt_id=str(attempt["attempt_id"]), | |
| ) | |
| except (PaymentError, PaymentRejected) as exc: | |
| return html( | |
| views.donation_payment( | |
| donation, | |
| account_of(request), | |
| error=f"The local sandbox could not complete this attempt: {exc}", | |
| ), | |
| 400, | |
| ) | |
| return see_other(f"/donate/{project_slug}/review?donation_id={donation_id}") | |
| def donation_review(request: Request, project_slug: str, donation_id: str = ""): | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| if donation["status"] == "confirmed": | |
| return see_other(f"/donations/{donation_id}/receipt") | |
| if not donation.get("payment_flow_id"): | |
| return see_other(f"/donate/{project_slug}/payment?donation_id={donation_id}") | |
| return html(views.donation_review(donation, account_of(request))) | |
| async def donation_review_post(request: Request, project_slug: str, donation_id: str = ""): | |
| form = await request.form() | |
| donation = _owned_donation(request, donation_id) | |
| if project_slug != PROJECT_SLUG or donation is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| if unexpected_fields(form, {"confirm"}): | |
| return html( | |
| views.donation_review( | |
| donation, | |
| account_of(request), | |
| error="This confirmation received an unsupported field.", | |
| ), | |
| 400, | |
| ) | |
| if donation["status"] == "confirmed": | |
| return see_other(f"/donations/{donation_id}/receipt") | |
| if str(form.get("confirm") or "") != "1": | |
| return html( | |
| views.donation_review( | |
| donation, | |
| account_of(request), | |
| error="Confirm that you understand this is a local simulation.", | |
| ), | |
| 400, | |
| ) | |
| try: | |
| with db() as connection: | |
| current = business.get_donation( | |
| connection, | |
| donation_id, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| ) | |
| if current is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| if current["status"] == "confirmed": | |
| return see_other(f"/donations/{donation_id}/receipt") | |
| facts = business.payment_facts(current) | |
| consumed = BACKEND.payments.consume_approval( | |
| connection, | |
| flow_id=str(current["payment_flow_id"]), | |
| owner=facts["owner"], | |
| amount_minor=facts["amount_minor"], | |
| currency=facts["currency"], | |
| fingerprint=facts["fingerprint"], | |
| ) | |
| confirmed = business.confirm_donation( | |
| connection, | |
| donation_id=donation_id, | |
| owner_key=owner_key_of(request), | |
| account_id=account_id_of(request), | |
| payment_flow_id=str(current["payment_flow_id"]), | |
| payment_attempt_id=str(consumed["attempt_id"]), | |
| ) | |
| if confirmed is None: | |
| raise PaymentError("local donation transition was unavailable") | |
| except (PaymentError, PaymentRejected) as exc: | |
| return html( | |
| views.donation_review( | |
| donation, | |
| account_of(request), | |
| error=f"The local confirmation was not created: {exc}", | |
| ), | |
| 400, | |
| ) | |
| return see_other(f"/donations/{donation_id}/receipt") | |
| def donation_receipt(request: Request, donation_id: str): | |
| donation = _owned_donation(request, donation_id) | |
| if donation is None or donation["status"] != "confirmed": | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.receipt(donation, account_of(request))) | |
| # Account, registration, and recovery ----------------------------------------- | |
| def login_page(request: Request, email: str = "", next: str = "/account"): | |
| if account_of(request): | |
| return see_other(safe_next(next)) | |
| return html(views.sign_in(email=email, next_url=safe_next(next))) | |
| async def login_post(request: Request): | |
| form = await request.form() | |
| email = str(form.get("email") or "").strip() | |
| next_url = safe_next(form.get("next")) | |
| old_owner = owner_key_of(request) | |
| try: | |
| result = AUTH.sign_in( | |
| str(request.state.auth_token), | |
| email=email, | |
| password=str(form.get("password") or ""), | |
| ) | |
| except AuthError: | |
| return html( | |
| views.sign_in( | |
| email=email, | |
| error="The email or password is incorrect.", | |
| next_url=next_url, | |
| ), | |
| 400, | |
| ) | |
| request.state.auth_token = result["session_token"] | |
| request.state.auth_info = {"authenticated": True, "account": result["account"]} | |
| with db() as connection: | |
| business.claim_donations( | |
| connection, | |
| owner_key=old_owner, | |
| account_id=str(result["account"]["account_id"]), | |
| ) | |
| return see_other(next_url) | |
| def register_page(request: Request): | |
| if account_of(request): | |
| return see_other("/account") | |
| return html(views.register()) | |
| async def register_post(request: Request): | |
| form = await request.form() | |
| values = { | |
| "display_name": str(form.get("display_name") or "").strip(), | |
| "email": str(form.get("email") or "").strip(), | |
| } | |
| if str(form.get("terms") or "") != "1": | |
| return html( | |
| views.register(values=values, error="Accept the local terms to continue."), | |
| 400, | |
| ) | |
| try: | |
| AUTH.start_registration( | |
| str(request.state.auth_token), | |
| email=values["email"], | |
| display_name=values["display_name"], | |
| password=str(form.get("password") or ""), | |
| restart_invalid_flow=True, | |
| ) | |
| except AuthRateLimited as exc: | |
| return html( | |
| views.register(values=values, error=f"Try again in {exc.retry_after} seconds."), | |
| 429, | |
| ) | |
| except (AuthConflict, AuthError) as exc: | |
| return html(views.register(values=values, error=str(exc)), 400) | |
| mail = AUTH.local_mail_for_session( | |
| str(request.state.auth_token), purpose="registration" | |
| ) | |
| code = str(mail.get("verification_code") or "") if mail else "" | |
| return html(views.register(code=code)) | |
| async def register_verify_post(request: Request): | |
| form = await request.form() | |
| old_owner = owner_key_of(request) | |
| try: | |
| AUTH.verify_registration_code( | |
| str(request.state.auth_token), str(form.get("code") or "") | |
| ) | |
| result = AUTH.complete_registration(str(request.state.auth_token)) | |
| except AuthError as exc: | |
| mail = AUTH.local_mail_for_session( | |
| str(request.state.auth_token), purpose="registration" | |
| ) | |
| code = str(mail.get("verification_code") or "") if mail else "" | |
| return html(views.register(code=code, error=str(exc)), 400) | |
| request.state.auth_token = result["session_token"] | |
| request.state.auth_info = {"authenticated": True, "account": result["account"]} | |
| with db() as connection: | |
| business.claim_donations( | |
| connection, | |
| owner_key=old_owner, | |
| account_id=str(result["account"]["account_id"]), | |
| ) | |
| return see_other("/account?notice=Account+created") | |
| def forgot_password(): | |
| return html(views.recover()) | |
| async def forgot_password_post(request: Request): | |
| form = await request.form() | |
| try: | |
| result = AUTH.start_password_reset( | |
| str(request.state.auth_token), | |
| email=str(form.get("email") or ""), | |
| restart_invalid_flow=True, | |
| ) | |
| except AuthRateLimited as exc: | |
| return html(views.recover(error=f"Try again in {exc.retry_after} seconds."), 429) | |
| except AuthError as exc: | |
| return html(views.recover(error=str(exc)), 400) | |
| mail = AUTH.local_mail_for_session( | |
| str(request.state.auth_token), purpose="password-reset" | |
| ) | |
| code = str(mail.get("verification_code") or "") if mail else "" | |
| return html(views.recover(message=str(result["message"]), code=code)) | |
| async def forgot_password_complete(request: Request): | |
| form = await request.form() | |
| try: | |
| AUTH.verify_password_reset_code( | |
| str(request.state.auth_token), str(form.get("code") or "") | |
| ) | |
| token = AUTH.complete_password_reset( | |
| str(request.state.auth_token), | |
| new_password=str(form.get("password") or ""), | |
| ) | |
| except AuthError as exc: | |
| mail = AUTH.local_mail_for_session( | |
| str(request.state.auth_token), purpose="password-reset" | |
| ) | |
| code = str(mail.get("verification_code") or "") if mail else "" | |
| return html( | |
| views.recover( | |
| message="Use the local reset code to choose a new password.", | |
| error=str(exc), | |
| code=code, | |
| ), | |
| 400, | |
| ) | |
| request.state.auth_token = token | |
| request.state.auth_info = AUTH.resolve_session(token) or {} | |
| return see_other("/account?notice=Password+updated") | |
| def logout(request: Request): | |
| AUTH.sign_out(str(request.state.auth_token)) | |
| token = AUTH.create_anonymous_session() | |
| request.state.auth_token = token | |
| request.state.auth_info = {"authenticated": False, "account": None} | |
| return see_other("/") | |
| def account_dashboard(request: Request, notice: str = ""): | |
| account = account_of(request) | |
| if account is None: | |
| return see_other("/login?next=/account") | |
| with db() as connection: | |
| donations = business.list_donations(connection, str(account["account_id"])) | |
| recurring = business.list_recurring(connection, str(account["account_id"])) | |
| return html(views.account_dashboard(account, donations, recurring, notice)) | |
| def donation_history(request: Request): | |
| account = account_of(request) | |
| if account is None: | |
| return see_other("/login?next=/account/donations") | |
| with db() as connection: | |
| donations = business.list_donations(connection, str(account["account_id"])) | |
| return html(views.donation_history(account, donations)) | |
| def recurring_plans(request: Request, notice: str = ""): | |
| account = account_of(request) | |
| if account is None: | |
| return see_other("/login?next=/account/recurring") | |
| with db() as connection: | |
| plans = business.list_recurring(connection, str(account["account_id"])) | |
| return html(views.recurring_plans(account, plans, notice)) | |
| def cancel_recurring(request: Request, plan_id: str): | |
| account = account_of(request) | |
| if account is None: | |
| return see_other("/login?next=/account/recurring") | |
| with db() as connection: | |
| result = business.cancel_recurring( | |
| connection, plan_id, str(account["account_id"]) | |
| ) | |
| if result is None: | |
| return html(views.not_found(account), 404) | |
| return see_other("/account/recurring?notice=Local+recurring+plan+canceled") | |
| def reference_detail(request: Request, section: str, slug: str): | |
| title = REFERENCE_TITLES.get(section, {}).get(slug) | |
| if title is None: | |
| return html(views.not_found(account_of(request)), 404) | |
| return html(views.reference_detail(section, title, account_of(request))) | |
| def not_found(request: Request, path: str): | |
| return html(views.not_found(account_of(request)), 404) | |