diff --git a/README.md b/README.md index d73f5e6..ed78ff5 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,27 @@ from `.python-version`. The `release` phase in the `Procfile` runs $ git push heroku master ``` +## Admin and cleanup + +`/admin/` lists every pin with flags for ones that look wrong: not in any +country (out at sea), duplicates of an older pin, and links in the location +or nickname. Filter by flag, select, and delete in bulk. + +New pins store their country when they're added. To check older pins, run +this once (it calls Nominatim about once per second, and can be stopped and +rerun): + +```console +$ heroku run -a members-map flask --app members_map check-pins +``` + +## 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..a5b8b89 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, checks, 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) @@ -28,7 +28,9 @@ def create_app(config: dict | None = None) -> Flask: logging.basicConfig(level=logging.INFO) db.init_app(app) + checks.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..d4e35ca --- /dev/null +++ b/members_map/admin.py @@ -0,0 +1,109 @@ +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 checks, 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() + flags = checks.flag_pins(all_pins) + counts = { + flag: sum(flag in reasons for reasons in flags.values()) + for flag in checks.FLAGS + } + return render_template( + "admin.html", + pins=list(reversed(all_pins)), + flags=flags, + counts=counts, + unchecked=sum(p.country is None for p in 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_pins(): + ids = [int(i) for i in request.form.getlist("id") if i.isdigit()] + if not ids: + flash("No pins selected.", "error") + return redirect(url_for("admin.pins")) + deleted = db.delete_pins(ids) + log.info("Admin deleted pins %s", ids) + flash(f"Deleted {deleted} pin{'' if deleted == 1 else 's'}.", "success") + 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, + "country": p.country, + } + 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/checks.py b/members_map/checks.py new file mode 100644 index 0000000..ca35f84 --- /dev/null +++ b/members_map/checks.py @@ -0,0 +1,81 @@ +import re +import time +from collections.abc import Iterable + +import click +from flask import Flask +from flask.cli import with_appcontext + +from members_map import db, geo + +NOT_IN_COUNTRY = "not in a country" +DUPLICATE = "duplicate" +LINK = "contains a link" +FLAGS = (NOT_IN_COUNTRY, DUPLICATE, LINK) + +LINK_PATTERN = re.compile( + r"https?://|www\.|\.(com|net|org|io|ru|xyz|info|biz)\b", re.IGNORECASE +) + +# Nominatim allows at most one request per second +NOMINATIM_DELAY = 1.1 + + +def flag_pins(pins: Iterable[db.Pin]) -> dict[int, list[str]]: + """Reasons each pin looks wrong, keyed by pin id. Clean pins are left out. + + For duplicates, the oldest pin stays unflagged so deleting every + flagged duplicate keeps one copy. + """ + flags: dict[int, list[str]] = {} + seen: set[tuple[str, str]] = set() + for pin in sorted(pins, key=lambda p: p.id or 0): + reasons = [] + if pin.country == "": + reasons.append(NOT_IN_COUNTRY) + key = (pin.location.strip().lower(), (pin.nickname or "").lower()) + if key in seen: + reasons.append(DUPLICATE) + seen.add(key) + if LINK_PATTERN.search(f"{pin.location} {pin.nickname or ''}"): + reasons.append(LINK) + if reasons: + flags[pin.id] = reasons + return flags + + +def find_country(pin: db.Pin) -> str: + """Country for a pin from its typed text, else its coordinates.""" + place = geo.geocode(pin.location) + if place is None: + time.sleep(NOMINATIM_DELAY) + place = geo.reverse(pin.latitude, pin.longitude) + return place.country if place else "" + + +@click.command("check-pins") +@with_appcontext +def check_pins_command() -> None: + """Look up the country of every pin that hasn't been checked yet. + + Safe to stop and rerun: it continues with the pins still unchecked. + """ + pins = db.unchecked_pins() + click.echo(f"Checking {len(pins)} pins, about one per second.") + for done, pin in enumerate(pins, 1): + try: + country = find_country(pin) + except geo.GeocodingUnavailable: + click.echo("Nominatim isn't answering. Run this again later.") + raise SystemExit(1) from None + db.set_country(pin.id, country) + if not country: + click.echo(f" #{pin.id} {pin.location!r}: not in a country") + if done % 50 == 0: + click.echo(f"{done}/{len(pins)} checked") + time.sleep(NOMINATIM_DELAY) + click.echo("Done.") + + +def init_app(app: Flask) -> None: + app.cli.add_command(check_pins_command) diff --git a/members_map/db.py b/members_map/db.py index 391cd5d..dd003c0 100644 --- a/members_map/db.py +++ b/members_map/db.py @@ -5,6 +5,7 @@ import click import psycopg from flask import Flask, current_app, g +from flask.cli import with_appcontext from psycopg.rows import class_row @@ -14,6 +15,13 @@ class Pin: latitude: float longitude: float nickname: str | None + # None: not checked yet. "": checked, and not in any country. + country: str | None = None + id: int | None = None + created: datetime | None = None + + +PIN_COLUMNS = "location, latitude, longitude, nickname, country, id, created" def get_db() -> psycopg.Connection: @@ -38,28 +46,62 @@ 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() def add_pin(pin: Pin) -> None: conn = get_db() conn.execute( - "INSERT INTO data (location, latitude, longitude, created, nickname)" - " VALUES (%s, %s, %s, %s, %s)", + "INSERT INTO data" + " (location, latitude, longitude, created, nickname, country)" + " VALUES (%s, %s, %s, %s, %s, %s)", ( pin.location, pin.latitude, pin.longitude, datetime.now(UTC).replace(tzinfo=None), pin.nickname, + pin.country, ), ) 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_pins(pin_ids: list[int]) -> int: + conn = get_db() + cur = conn.execute("DELETE FROM data WHERE id = ANY(%s)", (pin_ids,)) + conn.commit() + return cur.rowcount + + +def unchecked_pins() -> list[Pin]: + with get_db().cursor(row_factory=class_row(Pin)) as cur: + return cur.execute( + f"SELECT {PIN_COLUMNS} FROM data WHERE country IS NULL ORDER BY id" + ).fetchall() + + +def set_country(pin_id: int, country: str) -> None: + conn = get_db() + conn.execute( + "UPDATE data SET country = %s WHERE id = %s", (country, pin_id) + ) + conn.commit() + + @click.command("init-db") +@with_appcontext def init_db_command() -> None: """Create the pins table if it doesn't exist.""" init_db() 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..f1a97ed --- /dev/null +++ b/members_map/geo.py @@ -0,0 +1,73 @@ +from dataclasses import dataclass + +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 + +TOWN_KEYS = ("city", "town", "village", "municipality", "county") + + +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) + + +@dataclass(frozen=True) +class Place: + name: str + country: str + latitude: float + longitude: float + + +def _place(result, name: str | None = None) -> Place | None: + """Turn a Nominatim result into a Place, or None if not in a country. + + Requiring a country keeps out oceans, seas and other places nobody + lives, like "Atlantic Ocean". + """ + address = result.raw.get("address", {}) if result else {} + country = address.get("country") + if not country: + return None + if name is None: + town = next( + (address[key] for key in TOWN_KEYS if key in address), + None, + ) + name = ", ".join(p for p in (town, country) if p) + return Place(name, country, result.latitude, result.longitude) + + +def geocode(location: str) -> Place | None: + """Look up a typed place. The Place keeps the typed text as its name.""" + try: + result = _geolocator().geocode( + location, addressdetails=True, language="en" + ) + except GeopyError as err: + raise GeocodingUnavailable from err + return _place(result, name=location) + + +def reverse(lat: float, lng: float) -> Place | None: + """Town-level Place, named 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 + return _place(result) diff --git a/members_map/schema.sql b/members_map/schema.sql index 9d29a97..cfcf21f 100644 --- a/members_map/schema.sql +++ b/members_map/schema.sql @@ -6,3 +6,15 @@ CREATE TABLE IF NOT EXISTS data ( created TIMESTAMP NOT NULL, nickname TEXT ); + +-- NULL: not checked yet. Empty: checked, and not in any country. +ALTER TABLE data ADD COLUMN IF NOT EXISTS country 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..4254c84 --- /dev/null +++ b/members_map/static/admin.js @@ -0,0 +1,59 @@ +(function () { + "use strict"; + + const search = document.getElementById("filter"); + const flagFilter = document.getElementById("flag-filter"); + const selectAll = document.getElementById("select-all"); + const bulkForm = document.getElementById("bulk-delete"); + const bulkButton = bulkForm.querySelector("button"); + const rows = [...document.querySelectorAll("tbody tr")]; + const checkbox = (row) => row.querySelector("input[name=id]"); + + function matches(row) { + const query = search.value.trim().toLowerCase(); + const flag = flagFilter.value; + const flags = row.dataset.flags ? row.dataset.flags.split("|") : []; + if (query && !row.dataset.search.includes(query)) return false; + if (flag === "flagged") return flags.length > 0; + return !flag || flags.includes(flag); + } + + function selected() { + return rows.filter((row) => !row.hidden && checkbox(row).checked); + } + + function update() { + const count = selected().length; + bulkButton.disabled = count === 0; + bulkButton.textContent = count + ? `Delete ${count} selected` + : "Delete selected"; + } + + function applyFilters() { + for (const row of rows) { + row.hidden = !matches(row); + if (row.hidden) checkbox(row).checked = false; + } + selectAll.checked = false; + update(); + } + + search.addEventListener("input", applyFilters); + flagFilter.addEventListener("change", applyFilters); + selectAll.addEventListener("change", () => { + for (const row of rows) { + if (!row.hidden) checkbox(row).checked = selectAll.checked; + } + update(); + }); + document.querySelector("tbody").addEventListener("change", update); + + bulkForm.addEventListener("submit", (event) => { + const count = selected().length; + const noun = count === 1 ? "pin" : "pins"; + if (!window.confirm(`Delete ${count} ${noun}? This can't be undone.`)) { + event.preventDefault(); + } + }); +})(); diff --git a/members_map/static/map.js b/members_map/static/map.js index b13a0ec..f16d0e2 100644 --- a/members_map/static/map.js +++ b/members_map/static/map.js @@ -22,3 +22,56 @@ } 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; + + // About 1 km: enough for the server to find your town, which it then + // stores at about 10 km + function round(value) { + return Math.round(value * 100) / 100; + } + + 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..2cfc173 100644 --- a/members_map/static/style.css +++ b/members_map/static/style.css @@ -87,3 +87,193 @@ 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:not([type="checkbox"]) { + width: 100%; + min-width: 10rem; +} + +.admin-page .coords { + white-space: nowrap; + color: #555; +} + +.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; +} + +.admin-page .toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + align-items: center; +} + +.admin-page select { + padding: 0.4rem 0.5rem; + font: inherit; + border: 1px solid #bbb; + border-radius: 4px; +} + +.admin-page .notice { + padding: 0.5rem 0.75rem; + font-size: 0.9rem; + background: #fff8e1; + border: 1px solid #f0d58c; + border-radius: 4px; +} + +.admin-page tr.flagged { + background: #fff4f4; +} + +.admin-page .flag { + display: inline-block; + margin: 0 0.25rem 0.15rem 0; + padding: 0.05rem 0.4rem; + font-size: 0.75rem; + color: #8c0019; + background: #fde2e4; + border-radius: 999px; + white-space: nowrap; +} + +.admin-page .muted { + color: #888; +} + +.admin-page .country { + white-space: nowrap; +} + +.admin-page th:first-child, +.admin-page td:first-child { + width: 1%; +} + +.admin-page th { + white-space: nowrap; +} 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..766666b --- /dev/null +++ b/members_map/templates/admin.html @@ -0,0 +1,92 @@ +{% 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 +

+ {% if unchecked %} +

+ Pins not checked for a country yet: {{ "{:,}".format(unchecked) }}. + Run heroku run -a members-map flask --app members_map check-pins + (about one pin per second) to flag the ones out at sea. +

+ {% endif %} +
+ + +
+ + +
+
+ {% include "_flashes.html" %} +
+
+ + + + + + + + + + + + + + + {% for pin in pins %} + {% set reasons = flags.get(pin.id, []) %} + + + + + + + + + + + {% endfor %} + +
IDAdded (UTC)LocationNicknameCountryFlags
+ + {{ pin.id }}{{ pin.created.strftime("%Y-%m-%d") if pin.created }} + + + + + {%- if pin.country is none %}not checked + {%- elif pin.country %}{{ pin.country }} + {%- else %}none{% endif -%} + + {% for reason in reasons %}{{ reason }}{% endfor %} + +
+ + +
+
+
+ +{% 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..5122272 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

+ +

+ 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. It rounds your coordinates + to about 1 km before sending them, so we never see your exact + position. We use them once to look up your town name, then store + the pin rounded to about 10 km like every other pin. +

+

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..43292ac 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)" +NOT_ON_LAND = ( + "That spot doesn't seem to be in a country. Please type your city instead." ) -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) -> geo.Place | str: + """Return the Place for the submitted form, or an error message.""" + coords = _browser_coords() + if coords: + # Name the place before fuzzing: rounding a coastal town to 10 km + # can land out at sea + return geo.reverse(*coords) or NOT_ON_LAND + if not location: + return "Please enter a city and country." + return geo.geocode(location) or ( + "We couldn't find that place. Please enter a city and country, " + "like Vancouver, Canada." + ) @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") + lat, lng = geo.fuzz(result.latitude, result.longitude) + db.add_pin(db.Pin(result.name, lat, lng, nickname, result.country)) + log.info("New location: %r (%s, %s)", result.name, 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..2f2aa4c 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(): @@ -34,8 +34,14 @@ def client(app): @pytest.fixture def add_pin(app): - def _add(location="Berlin, Germany", lat=52.5, lng=13.4, nickname=None): + def _add( + location="Berlin, Germany", + lat=52.5, + lng=13.4, + nickname=None, + country=None, + ): with app.app_context(): - db.add_pin(db.Pin(location, lat, lng, nickname)) + db.add_pin(db.Pin(location, lat, lng, nickname, country)) return _add diff --git a/tests/test_admin.py b/tests/test_admin.py new file mode 100644 index 0000000..412ace9 --- /dev/null +++ b/tests/test_admin.py @@ -0,0 +1,186 @@ +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 "