Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
Expand Down
6 changes: 4 additions & 2 deletions members_map/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -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)
Expand All @@ -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:
Expand Down
109 changes: 109 additions & 0 deletions members_map/admin.py
Original file line number Diff line number Diff line change
@@ -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/<int:pin_id>")
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"
},
)
81 changes: 81 additions & 0 deletions members_map/checks.py
Original file line number Diff line number Diff line change
@@ -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)
50 changes: 46 additions & 4 deletions members_map/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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:
Expand All @@ -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()
Expand Down
31 changes: 31 additions & 0 deletions members_map/forms.py
Original file line number Diff line number Diff line change
@@ -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.")
Loading
Loading