From 7fcd3f067cbbf335e4b0db9891bcec772fd0f6fa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 23:00:31 +0000 Subject: [PATCH 1/3] Add admin page, browser location, privacy explainer - /admin/ behind HTTP basic auth (ADMIN_PASSWORD): list and filter pins, edit location and nickname, delete, export JSON. Replaces /export/json and EXPORT_PASSWORD. Forms carry a session CSRF token since browsers resend basic auth automatically. - "Use my current location" button: coordinates are rounded to one decimal (about 11 km) in the browser and again on the server, and the label comes from a Nominatim reverse lookup at town level. - Every pin is now stored at about 11 km precision, including typed locations. The release phase rounds existing pins too (idempotent). - Privacy explainer dialog on the map page, honeypot spam field, member count in the header. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WLRZ1bCeX4qyg1QpD6AQFG --- README.md | 9 +- members_map/__init__.py | 5 +- members_map/admin.py | 98 +++++++++++++++ members_map/db.py | 25 +++- members_map/forms.py | 31 +++++ members_map/geo.py | 53 ++++++++ members_map/schema.sql | 9 ++ members_map/static/admin.js | 22 ++++ members_map/static/map.js | 51 ++++++++ members_map/static/style.css | 141 +++++++++++++++++++++ members_map/templates/_flashes.html | 3 + members_map/templates/admin.html | 61 +++++++++ members_map/templates/base.html | 13 ++ members_map/templates/index.html | 92 +++++++++++--- members_map/views.py | 147 +++++++++------------- tests/conftest.py | 2 +- tests/test_admin.py | 168 +++++++++++++++++++++++++ tests/test_views.py | 188 +++++++++++++++++++++++----- 18 files changed, 982 insertions(+), 136 deletions(-) create mode 100644 members_map/admin.py create mode 100644 members_map/forms.py create mode 100644 members_map/geo.py create mode 100644 members_map/static/admin.js create mode 100644 members_map/templates/_flashes.html create mode 100644 members_map/templates/admin.html create mode 100644 members_map/templates/base.html create mode 100644 tests/test_admin.py diff --git a/README.md b/README.md index d73f5e6..e0317ec 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ $ uv run ruff check . && uv run ruff format --check . | --- | --- | | `DATABASE_URL` | Postgres connection URL (set by Heroku Postgres) | | `SECRET_KEY` | Signs the session cookie used for flash messages | -| `EXPORT_PASSWORD` | Enables `/export/json` behind HTTP basic auth (any username). Unset means the endpoint returns 404 | +| `ADMIN_PASSWORD` | Enables the admin page at `/admin/` (HTTP basic auth, any username): edit, delete and export pins. Unset means `/admin/` returns 404 | ## Deployment @@ -48,6 +48,13 @@ from `.python-version`. The `release` phase in the `Procfile` runs $ git push heroku master ``` +## Privacy + +Pins are stored at one decimal place (about 11 km). The server rounds every +new pin, the "Use my current location" button rounds in the browser too, and +the release phase rounds any older pins (`schema.sql`). The explainer on the +map page describes this to members; keep it in sync if anything changes. + ## Tile usage OpenStreetMap's tile servers require a valid `Referer` on every tile request. diff --git a/members_map/__init__.py b/members_map/__init__.py index ba3c577..ae5b55f 100644 --- a/members_map/__init__.py +++ b/members_map/__init__.py @@ -7,7 +7,7 @@ from flask import Flask -from members_map import db, views +from members_map import admin, db, views log = logging.getLogger(__name__) @@ -17,7 +17,7 @@ def create_app(config: dict | None = None) -> Flask: app.config.from_mapping( DATABASE_URL=os.environ.get("DATABASE_URL"), SECRET_KEY=os.environ.get("SECRET_KEY"), - EXPORT_PASSWORD=os.environ.get("EXPORT_PASSWORD"), + ADMIN_PASSWORD=os.environ.get("ADMIN_PASSWORD"), ) if config: app.config.from_mapping(config) @@ -29,6 +29,7 @@ def create_app(config: dict | None = None) -> Flask: logging.basicConfig(level=logging.INFO) db.init_app(app) app.register_blueprint(views.bp) + app.register_blueprint(admin.bp) @cache def static_version(filename: str) -> str: diff --git a/members_map/admin.py b/members_map/admin.py new file mode 100644 index 0000000..4c220c8 --- /dev/null +++ b/members_map/admin.py @@ -0,0 +1,98 @@ +import hmac +import json +import logging + +from flask import ( + Blueprint, + Response, + abort, + current_app, + flash, + redirect, + render_template, + request, + url_for, +) + +from members_map import db, forms + +log = logging.getLogger(__name__) +bp = Blueprint("admin", __name__, url_prefix="/admin") + + +@bp.before_request +def require_password(): + password = current_app.config["ADMIN_PASSWORD"] + if not password: + abort(404) + auth = request.authorization + if auth is None or not hmac.compare_digest( + (auth.password or "").encode(), password.encode() + ): + return Response( + "Authentication required", + 401, + {"WWW-Authenticate": 'Basic realm="members-map admin"'}, + ) + if request.method == "POST": + forms.check_csrf() + return None + + +@bp.get("/") +def pins(): + all_pins = db.all_pins() + return render_template( + "admin.html", + pins=list(reversed(all_pins)), + csrf=forms.csrf_token(), + ) + + +@bp.post("/pins/") +def update_pin(pin_id: int): + location = request.form.get("location", "").strip() + nickname = forms.clean_nickname(request.form.get("nickname")) + error = forms.validation_error(location, nickname) + if not location: + error = "Location can't be empty." + if error: + flash(f"Pin {pin_id}: {error}", "error") + elif db.update_pin(pin_id, location, nickname): + log.info("Admin updated pin %s: %r %r", pin_id, location, nickname) + flash(f"Pin {pin_id} updated.", "success") + else: + flash(f"Pin {pin_id} doesn't exist anymore.", "error") + return redirect(url_for("admin.pins")) + + +@bp.post("/pins//delete") +def delete_pin(pin_id: int): + if db.delete_pin(pin_id): + log.info("Admin deleted pin %s", pin_id) + flash(f"Pin {pin_id} deleted.", "success") + else: + flash(f"Pin {pin_id} doesn't exist anymore.", "error") + return redirect(url_for("admin.pins")) + + +@bp.get("/export.json") +def export_json(): + pins = [ + { + "id": p.id, + "created": p.created.isoformat() if p.created else None, + "location": p.location, + "latitude": p.latitude, + "longitude": p.longitude, + "nickname": p.nickname, + } + for p in db.all_pins() + ] + return Response( + json.dumps(pins, indent=2, ensure_ascii=False), + mimetype="application/json", + headers={ + "Content-Disposition": "attachment; filename=members-map.json" + }, + ) diff --git a/members_map/db.py b/members_map/db.py index 391cd5d..dcf3c92 100644 --- a/members_map/db.py +++ b/members_map/db.py @@ -14,6 +14,11 @@ class Pin: latitude: float longitude: float nickname: str | None + id: int | None = None + created: datetime | None = None + + +PIN_COLUMNS = "location, latitude, longitude, nickname, id, created" def get_db() -> psycopg.Connection: @@ -38,8 +43,7 @@ def init_db() -> None: def all_pins() -> list[Pin]: with get_db().cursor(row_factory=class_row(Pin)) as cur: return cur.execute( - "SELECT location, latitude, longitude, nickname" - " FROM data ORDER BY id" + f"SELECT {PIN_COLUMNS} FROM data ORDER BY id" ).fetchall() @@ -59,6 +63,23 @@ def add_pin(pin: Pin) -> None: conn.commit() +def update_pin(pin_id: int, location: str, nickname: str | None) -> bool: + conn = get_db() + cur = conn.execute( + "UPDATE data SET location = %s, nickname = %s WHERE id = %s", + (location, nickname, pin_id), + ) + conn.commit() + return cur.rowcount == 1 + + +def delete_pin(pin_id: int) -> bool: + conn = get_db() + cur = conn.execute("DELETE FROM data WHERE id = %s", (pin_id,)) + conn.commit() + return cur.rowcount == 1 + + @click.command("init-db") def init_db_command() -> None: """Create the pins table if it doesn't exist.""" diff --git a/members_map/forms.py b/members_map/forms.py new file mode 100644 index 0000000..a127ead --- /dev/null +++ b/members_map/forms.py @@ -0,0 +1,31 @@ +import hmac +import secrets + +from flask import abort, request, session + +MAX_LOCATION_LENGTH = 200 +MAX_NICKNAME_LENGTH = 50 + + +def clean_nickname(raw: str | None) -> str | None: + return (raw or "").strip() or None + + +def validation_error(location: str, nickname: str | None) -> str | None: + if len(location) > MAX_LOCATION_LENGTH: + return "That location is too long." + if nickname and len(nickname) > MAX_NICKNAME_LENGTH: + return f"Nicknames can be at most {MAX_NICKNAME_LENGTH} characters." + return None + + +def csrf_token() -> str: + if "csrf" not in session: + session["csrf"] = secrets.token_urlsafe(32) + return session["csrf"] + + +def check_csrf() -> None: + sent = request.form.get("csrf", "") + if not hmac.compare_digest(sent, session.get("csrf", "")): + abort(400, "Form expired, please reload the page and try again.") diff --git a/members_map/geo.py b/members_map/geo.py new file mode 100644 index 0000000..95e9d6f --- /dev/null +++ b/members_map/geo.py @@ -0,0 +1,53 @@ +from geopy.exc import GeopyError +from geopy.geocoders import Nominatim + +USER_AGENT = "realpython-members-map/2.0 (+https://members-map.realpython.com)" + +# One decimal place is about 11 km: close enough to show the town, too +# coarse to point at anyone's home. +PRECISION = 1 + + +class GeocodingUnavailable(Exception): + pass + + +def fuzz(lat: float, lng: float) -> tuple[float, float]: + return round(lat, PRECISION), round(lng, PRECISION) + + +def _geolocator() -> Nominatim: + return Nominatim(user_agent=USER_AGENT, timeout=5) + + +def geocode(location: str) -> tuple[float, float] | None: + try: + result = _geolocator().geocode(location) + except GeopyError as err: + raise GeocodingUnavailable from err + if result is None: + return None + return result.latitude, result.longitude + + +def place_name(lat: float, lng: float) -> str | None: + """Town-level name like "Vancouver, Canada" for a coordinate.""" + try: + result = _geolocator().reverse( + (lat, lng), zoom=10, language="en", exactly_one=True + ) + except GeopyError as err: + raise GeocodingUnavailable from err + if result is None: + return None + address = result.raw.get("address", {}) + town = next( + ( + address[key] + for key in ("city", "town", "village", "municipality", "county") + if key in address + ), + None, + ) + parts = [p for p in (town, address.get("country")) if p] + return ", ".join(parts) or None diff --git a/members_map/schema.sql b/members_map/schema.sql index 9d29a97..caa6e27 100644 --- a/members_map/schema.sql +++ b/members_map/schema.sql @@ -6,3 +6,12 @@ CREATE TABLE IF NOT EXISTS data ( created TIMESTAMP NOT NULL, nickname TEXT ); + +-- Pins are stored at about 10 km precision (see geo.PRECISION). This also +-- rounds pins added before that rule existed. It's idempotent, so it runs +-- on every release. +UPDATE data +SET latitude = round(latitude::numeric, 1), + longitude = round(longitude::numeric, 1) +WHERE latitude::numeric <> round(latitude::numeric, 1) + OR longitude::numeric <> round(longitude::numeric, 1); diff --git a/members_map/static/admin.js b/members_map/static/admin.js new file mode 100644 index 0000000..d130b21 --- /dev/null +++ b/members_map/static/admin.js @@ -0,0 +1,22 @@ +(function () { + "use strict"; + + const filter = document.getElementById("filter"); + const rows = document.querySelectorAll("tbody tr"); + filter.addEventListener("input", () => { + const query = filter.value.trim().toLowerCase(); + for (const row of rows) { + row.hidden = query !== "" && !row.dataset.search.includes(query); + } + }); + + for (const form of document.querySelectorAll(".delete-form")) { + form.addEventListener("submit", (event) => { + const row = form.closest("tr"); + const location = row.querySelector("input[name=location]").value; + if (!window.confirm(`Delete the pin for "${location}"?`)) { + event.preventDefault(); + } + }); + } +})(); diff --git a/members_map/static/map.js b/members_map/static/map.js index b13a0ec..0be93d3 100644 --- a/members_map/static/map.js +++ b/members_map/static/map.js @@ -22,3 +22,54 @@ } map.addLayer(cluster); })(); + +(function () { + "use strict"; + + const button = document.getElementById("use-my-location"); + const form = document.getElementById("add-form"); + const status = document.getElementById("geo-status"); + if (!navigator.geolocation) return; + button.hidden = false; + + function round(value) { + return Math.round(value * 10) / 10; + } + + function showStatus(message) { + status.textContent = message; + status.hidden = false; + } + + button.addEventListener("click", () => { + button.disabled = true; + showStatus("Finding your location…"); + navigator.geolocation.getCurrentPosition( + (position) => { + form.elements.lat.value = round(position.coords.latitude); + form.elements.lng.value = round(position.coords.longitude); + showStatus("Adding your approximate location…"); + form.submit(); + }, + () => { + button.disabled = false; + showStatus( + "We couldn't get your location. Please type your city instead.", + ); + }, + { enableHighAccuracy: false, timeout: 10000, maximumAge: 600000 }, + ); + }); +})(); + +(function () { + "use strict"; + + const dialog = document.getElementById("privacy"); + document + .getElementById("privacy-open") + .addEventListener("click", () => dialog.showModal()); + dialog.addEventListener("click", (event) => { + if (event.target === dialog) dialog.close(); + }); +})(); diff --git a/members_map/static/style.css b/members_map/static/style.css index 26b2706..6f0b7c9 100644 --- a/members_map/static/style.css +++ b/members_map/static/style.css @@ -87,3 +87,144 @@ button:hover { flex: 1; min-height: 300px; } + +.count { + margin-left: 0.5rem; + font-size: 0.9rem; + font-weight: normal; + color: #555; +} + +button.secondary { + color: #377ba8; + background: #fff; + border: 1px solid #377ba8; +} + +button.secondary:hover { + background: #eef5fa; +} + +button:disabled { + opacity: 0.6; + cursor: wait; +} + +button.danger { + background: #b00020; +} + +button.danger:hover { + background: #8c0019; +} + +.hint { + margin: 0.5rem 0 0; + font-size: 0.8rem; + color: #666; +} + +.honeypot { + position: absolute; + left: -10000px; + width: 1px; + height: 1px; + overflow: hidden; +} + +body.admin-page { + display: block; + height: auto; +} + +.admin-page main { + padding: 0 1rem 2rem; +} + +.admin-page input[type="search"] { + width: 24rem; +} + +.admin-page table { + width: 100%; + border-collapse: collapse; + font-size: 0.9rem; + background: #fff; +} + +.admin-page th, +.admin-page td { + padding: 0.3rem 0.5rem; + border-bottom: 1px solid #ddd; + text-align: left; + vertical-align: middle; +} + +.admin-page td input { + width: 100%; + min-width: 10rem; +} + +.admin-page .coords { + white-space: nowrap; + color: #555; +} + +.admin-page .actions { + display: flex; + gap: 0.4rem; +} + +.admin-page .actions button { + padding: 0.3rem 0.7rem; + font-size: 0.85rem; +} + +button.link { + padding: 0; + font-size: inherit; + font-weight: normal; + color: #377ba8; + background: none; + text-decoration: underline; +} + +button.link:hover { + background: none; + color: #2c6489; +} + +dialog { + max-width: 36rem; + max-height: 85vh; + padding: 1.25rem 1.5rem; + border: 0; + border-radius: 8px; + box-shadow: 0 10px 40px rgb(0 0 0 / 25%); + line-height: 1.45; +} + +dialog::backdrop { + background: rgb(0 0 0 / 40%); +} + +dialog h2 { + margin-top: 0; + font-size: 1.25rem; + color: #377ba8; +} + +dialog h3 { + margin: 1rem 0 0.25rem; + font-size: 1rem; +} + +dialog p, +dialog ul { + margin: 0.25rem 0; +} + +dialog form { + margin-top: 1rem; + text-align: right; +} diff --git a/members_map/templates/_flashes.html b/members_map/templates/_flashes.html new file mode 100644 index 0000000..088f436 --- /dev/null +++ b/members_map/templates/_flashes.html @@ -0,0 +1,3 @@ +{% for category, message in get_flashed_messages(with_categories=true) %} +

{{ message }}

+{% endfor %} diff --git a/members_map/templates/admin.html b/members_map/templates/admin.html new file mode 100644 index 0000000..9e91461 --- /dev/null +++ b/members_map/templates/admin.html @@ -0,0 +1,61 @@ +{% extends "base.html" %} + +{% block title %}Admin · Real Python Community Map{% endblock %} +{% block body_class %}admin-page{% endblock %} + +{% block body %} +
+

Community Map admin {{ "{:,}".format(pins | length) }} pins

+

+ View the map · + Download all pins as JSON +

+ + {% include "_flashes.html" %} +
+
+ + + + + + + + + + + + + {% for pin in pins %} + + + + + + + + + {% endfor %} + +
IDAdded (UTC)LocationNicknameLat, lng
{{ pin.id }}{{ pin.created.strftime("%Y-%m-%d %H:%M") if pin.created }} + + + + {{ "%.2f, %.2f" | format(pin.latitude, pin.longitude) }} +
+ + +
+
+ + +
+
+
+ +{% endblock %} diff --git a/members_map/templates/base.html b/members_map/templates/base.html new file mode 100644 index 0000000..a0e705f --- /dev/null +++ b/members_map/templates/base.html @@ -0,0 +1,13 @@ + + + + + + {% block title %}Real Python Community Map{% endblock %} + {% block head %}{% endblock %} + + + + {% block body %}{% endblock %} + + diff --git a/members_map/templates/index.html b/members_map/templates/index.html index fe2d709..7afe975 100644 --- a/members_map/templates/index.html +++ b/members_map/templates/index.html @@ -1,18 +1,20 @@ - - - - - - Real Python Community Map +{% extends "base.html" %} + +{% block head %} - - - +{% endblock %} + +{% block body_class %}map-page{% endblock %} + +{% block body %}
-

Real Python Community Map

-
+

+ Real Python Community Map + {{ "{:,}".format(pins | length) }} Pythonistas on the map +

+ + + + +
- {% for category, message in get_flashed_messages(with_categories=true) %} -

{{ message }}

- {% endfor %} +

+ Pins are rounded to about 10 km, so nobody can see where exactly you live. + +

+ + {% include "_flashes.html" %}
+ +

Your privacy on the community map

+

+ This map shows where Real Python community members are around the + world. Adding yourself is optional, and you can ask us to remove or + change your pin at any time. +

+

What we store

+
    +
  • + An approximate location. Coordinates are rounded to + one decimal place, which is roughly 10 km. That's enough to show + your town, but not your street or your home. +
  • +
  • A place name, like "Vancouver, Canada".
  • +
  • A nickname, only if you enter one.
  • +
  • When the pin was added.
  • +
+

+ We don't store your name, email address, IP address, or anything that + links a pin to your Real Python account. +

+

"Use my current location"

+

+ Your browser asks for permission first. Your coordinates are rounded + to about 10 km in your browser before they're sent, and rounded + again on our server. We never see or keep your exact position. +

+

Services we use

+

+ Map images come from + OpenStreetMap, + and place names are looked up with OpenStreetMap's Nominatim service. + Like any website, their servers see your IP address when your browser + loads map tiles. The only cookie we set remembers the "location added" + message between page loads. +

+

Removing your pin

+

+ Pins aren't tied to accounts, so contact us at + realpython.com/contact + with the place and nickname you used, and we'll remove it. +

+
+ +
+
+
- - +{% endblock %} diff --git a/members_map/views.py b/members_map/views.py index 80eb90f..0a44ad3 100644 --- a/members_map/views.py +++ b/members_map/views.py @@ -1,120 +1,95 @@ -import hmac -import json import logging from flask import ( Blueprint, - Response, - abort, - current_app, flash, redirect, render_template, request, url_for, ) -from geopy.exc import GeopyError -from geopy.geocoders import Nominatim -from members_map import db +from members_map import db, forms, geo log = logging.getLogger(__name__) bp = Blueprint("map", __name__) -MAX_LOCATION_LENGTH = 200 -MAX_NICKNAME_LENGTH = 50 -GEOCODER_USER_AGENT = ( - "realpython-members-map/2.0 (+https://members-map.realpython.com)" -) - - -class GeocodingUnavailable(Exception): - pass - - -def geocode(location: str) -> tuple[float, float] | None: - geolocator = Nominatim(user_agent=GEOCODER_USER_AGENT, timeout=5) - try: - result = geolocator.geocode(location) - except GeopyError as err: - raise GeocodingUnavailable from err - if result is None: - return None - return result.latitude, result.longitude - -def pins_for_map() -> list[dict]: +def pins_for_map(pins: list[db.Pin]) -> list[dict]: return [ {"lat": p.latitude, "lng": p.longitude, "name": p.nickname} - for p in db.all_pins() + for p in pins ] @bp.get("/") def index(): - return render_template("index.html", pins=pins_for_map()) + pins = db.all_pins() + return render_template("index.html", pins=pins_for_map(pins)) + + +def _browser_coords() -> tuple[float, float] | None: + try: + lat = float(request.form["lat"]) + lng = float(request.form["lng"]) + except KeyError, ValueError: + return None + # Also rejects nan and inf, which fail every comparison + if not (-90 <= lat <= 90 and -180 <= lng <= 180): + return None + return lat, lng + + +def _resolve(location: str) -> tuple[str, float, float] | str: + """Return (label, lat, lng) for the submitted form, or an error.""" + coords = _browser_coords() + if coords: + lat, lng = geo.fuzz(*coords) + try: + label = geo.place_name(lat, lng) + except geo.GeocodingUnavailable: + log.exception("Reverse geocoding failed for %s, %s", lat, lng) + label = None + return label or f"{lat}, {lng}", lat, lng + if not location: + return "Please enter a city and country." + coords = geo.geocode(location) + if coords is None: + return "Location not found, please try again." + return (location, *geo.fuzz(*coords)) @bp.post("/") def add_location(): + if request.form.get("website"): + # Honeypot field, hidden from people: only bots fill it in + log.info("Ignored a submission that filled in the honeypot") + flash("Your location was added to the map.", "success") + return redirect(url_for("map.index")) + location = request.form.get("location", "").strip() - nickname = request.form.get("nickname", "").strip() or None + nickname = forms.clean_nickname(request.form.get("nickname")) - if not location: - flash("Please enter a city and country.", "error") - elif len(location) > MAX_LOCATION_LENGTH: - flash("That location is too long.", "error") - elif nickname and len(nickname) > MAX_NICKNAME_LENGTH: + if error := forms.validation_error(location, nickname): + flash(error, "error") + return redirect(url_for("map.index")) + + try: + result = _resolve(location) + except geo.GeocodingUnavailable: + log.exception("Geocoding failed for %r", location) flash( - f"Nicknames can be at most {MAX_NICKNAME_LENGTH} characters.", + "We couldn't look up locations right now. Please try again " + "in a few minutes.", "error", ) + return redirect(url_for("map.index")) + + if isinstance(result, str): + flash(result, "error") else: - try: - coords = geocode(location) - except GeocodingUnavailable: - log.exception("Geocoding failed for %r", location) - flash( - "We couldn't look up locations right now. Please try again " - "in a few minutes.", - "error", - ) - else: - if coords is None: - flash("Location not found, please try again.", "error") - else: - lat, lng = coords - db.add_pin(db.Pin(location, lat, lng, nickname)) - log.info("New location: %r (%s, %s)", location, lat, lng) - flash("Your location was added to the map.", "success") + label, lat, lng = result + db.add_pin(db.Pin(label, lat, lng, nickname)) + log.info("New location: %r (%s, %s)", label, lat, lng) + flash("Your location was added to the map.", "success") return redirect(url_for("map.index")) - - -def _export_authorized() -> bool: - password = current_app.config["EXPORT_PASSWORD"] - if not password: - abort(404) - auth = request.authorization - return auth is not None and hmac.compare_digest( - (auth.password or "").encode(), password.encode() - ) - - -@bp.get("/export/json") -def export_json(): - if not _export_authorized(): - return Response( - "Authentication required", - 401, - {"WWW-Authenticate": 'Basic realm="members-map export"'}, - ) - headers = ["location", "latitude", "longitude", "nickname"] - rows = [ - [p.location, p.latitude, p.longitude, p.nickname] - for p in db.all_pins() - ] - return Response( - json.dumps([headers, rows], indent=4, ensure_ascii=True), - mimetype="application/json", - headers={"Content-Disposition": "attachment; filename=export.json"}, - ) diff --git a/tests/conftest.py b/tests/conftest.py index 223948f..6512510 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -16,7 +16,7 @@ def app(): "TESTING": True, "DATABASE_URL": TEST_DATABASE_URL, "SECRET_KEY": "test", - "EXPORT_PASSWORD": None, + "ADMIN_PASSWORD": None, } ) with app.app_context(): diff --git a/tests/test_admin.py b/tests/test_admin.py new file mode 100644 index 0000000..d456af1 --- /dev/null +++ b/tests/test_admin.py @@ -0,0 +1,168 @@ +import base64 +import re + +import pytest + +from members_map import db + +PASSWORD = "s3cret" + + +def auth(password: str = PASSWORD) -> dict: + token = base64.b64encode(f"admin:{password}".encode()).decode() + return {"Authorization": f"Basic {token}"} + + +@pytest.fixture +def admin_app(app): + app.config["ADMIN_PASSWORD"] = PASSWORD + return app + + +@pytest.fixture +def csrf(admin_app, client): + client.get("/admin/", headers=auth()) + with client.session_transaction() as session: + return session["csrf"] + + +def pins(app) -> list[db.Pin]: + with app.app_context(): + return db.all_pins() + + +def test_admin_is_hidden_without_password(client): + assert client.get("/admin/").status_code == 404 + assert client.get("/admin/export.json").status_code == 404 + + +@pytest.mark.parametrize("headers", [{}, auth("wrong")]) +def test_admin_requires_password(admin_app, client, headers): + response = client.get("/admin/", headers=headers) + + assert response.status_code == 401 + assert "Basic" in response.headers["WWW-Authenticate"] + + +def test_admin_lists_pins_newest_first(admin_app, client, add_pin): + add_pin(location="Berlin, Germany", nickname="Ada") + add_pin(location="Lima, Peru") + + html = client.get("/admin/", headers=auth()).text + + assert "2 pins" in html + assert html.index("Lima, Peru") < html.index("Berlin, Germany") + assert 'value="Ada"' in html + assert re.search(r'name="csrf" value="[^"]+"', html) + + +def test_admin_escapes_nicknames(admin_app, client, add_pin): + add_pin(nickname='">') + + html = client.get("/admin/", headers=auth()).text + + assert "