Skip to content

Commit af0966c

Browse files
authored
Merge pull request #4 from realpython/claude/project-thread-pm5duv
Sanity-check names and locations people submit
2 parents 497f4d5 + 7ed9cb4 commit af0966c

6 files changed

Lines changed: 119 additions & 18 deletions

File tree

‎members_map/admin.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ def pins():
5959

6060
@bp.post("/pins/<int:pin_id>")
6161
def update_pin(pin_id: int):
62-
location = request.form.get("location", "").strip()
63-
nickname = forms.clean_nickname(request.form.get("nickname"))
62+
location = forms.clean_text(request.form.get("location"))
63+
nickname = forms.clean_text(request.form.get("nickname")) or None
6464
error = forms.validation_error(location, nickname)
6565
if not location:
6666
error = "Location can't be empty."

‎members_map/checks.py‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,17 @@
1-
import re
21
import time
32
from collections.abc import Iterable
43

54
import click
65
from flask import Flask
76
from flask.cli import with_appcontext
87

9-
from members_map import db, geo
8+
from members_map import db, forms, geo
109

1110
NOT_IN_COUNTRY = "not in a country"
1211
DUPLICATE = "duplicate"
1312
LINK = "contains a link"
1413
FLAGS = (NOT_IN_COUNTRY, DUPLICATE, LINK)
1514

16-
LINK_PATTERN = re.compile(
17-
r"https?://|www\.|\.(com|net|org|io|ru|xyz|info|biz)\b", re.IGNORECASE
18-
)
1915

2016
# Nominatim allows at most one request per second
2117
NOMINATIM_DELAY = 1.1
@@ -37,7 +33,7 @@ def flag_pins(pins: Iterable[db.Pin]) -> dict[int, list[str]]:
3733
if key in seen:
3834
reasons.append(DUPLICATE)
3935
seen.add(key)
40-
if LINK_PATTERN.search(f"{pin.location} {pin.nickname or ''}"):
36+
if forms.LINK_PATTERN.search(f"{pin.location} {pin.nickname or ''}"):
4137
reasons.append(LINK)
4238
if reasons:
4339
flags[pin.id] = reasons

‎members_map/forms.py‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,70 @@
11
import hmac
2+
import re
23
import secrets
4+
import unicodedata
35

46
from flask import abort, request, session
57

68
MAX_LOCATION_LENGTH = 200
79
MAX_NICKNAME_LENGTH = 50
810

911

10-
def clean_nickname(raw: str | None) -> str | None:
11-
return (raw or "").strip() or None
12+
LINK_PATTERN = re.compile(
13+
r"https?://|www\.|\.(com|net|org|io|ru|xyz|info|biz)\b", re.IGNORECASE
14+
)
15+
EMAIL_PATTERN = re.compile(r"\S+@\S+\.\w{2,}")
16+
# Stacked accents ("Zalgo text"). Real scripts rarely need more than three
17+
# combining marks on one letter.
18+
MAX_COMBINING_RUN = 3
19+
ZERO_WIDTH_JOINER = "\u200d" # Keeps emoji like 👩‍💻 in one piece
1220

1321

14-
def validation_error(location: str, nickname: str | None) -> str | None:
15-
if len(location) > MAX_LOCATION_LENGTH:
16-
return "That location is too long."
17-
if nickname and len(nickname) > MAX_NICKNAME_LENGTH:
18-
return f"Nicknames can be at most {MAX_NICKNAME_LENGTH} characters."
22+
def clean_text(raw: str | None) -> str:
23+
"""Normalize Unicode, drop invisible characters, collapse whitespace."""
24+
text = unicodedata.normalize("NFKC", raw or "")
25+
text = "".join(
26+
ch
27+
for ch in text
28+
if ch == ZERO_WIDTH_JOINER
29+
or ch.isspace()
30+
or not unicodedata.category(ch).startswith("C")
31+
)
32+
return " ".join(text.split())
33+
34+
35+
def _too_many_combining_marks(text: str) -> bool:
36+
run = 0
37+
for ch in text:
38+
run = run + 1 if unicodedata.category(ch).startswith("M") else 0
39+
if run > MAX_COMBINING_RUN:
40+
return True
41+
return False
42+
43+
44+
def _text_error(text: str, field: str, max_length: int) -> str | None:
45+
if len(text) > max_length:
46+
return f"{field} can be at most {max_length} characters."
47+
if EMAIL_PATTERN.search(text):
48+
return (
49+
f"{field} can't contain an email address, because the map is "
50+
"public."
51+
)
52+
if LINK_PATTERN.search(text):
53+
return f"{field} can't contain links."
54+
if _too_many_combining_marks(text):
55+
return f"{field} has too many stacked accent marks."
56+
if text and not any(ch.isalnum() for ch in text):
57+
return f"{field} needs at least one letter or number."
1958
return None
2059

2160

61+
def validation_error(location: str, nickname: str | None) -> str | None:
62+
"""Expects text that already went through clean_text."""
63+
return _text_error(
64+
location, "Location", MAX_LOCATION_LENGTH
65+
) or _text_error(nickname or "", "Nickname", MAX_NICKNAME_LENGTH)
66+
67+
2268
def csrf_token() -> str:
2369
if "csrf" not in session:
2470
session["csrf"] = secrets.token_urlsafe(32)

‎members_map/views.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ def add_location():
6767
flash("Your location was added to the map.", "success")
6868
return redirect(url_for("map.index"))
6969

70-
location = request.form.get("location", "").strip()
71-
nickname = forms.clean_nickname(request.form.get("nickname"))
70+
location = forms.clean_text(request.form.get("location"))
71+
nickname = forms.clean_text(request.form.get("nickname")) or None
7272

7373
if error := forms.validation_error(location, nickname):
7474
flash(error, "error")

‎tests/test_forms.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import pytest
2+
3+
from members_map.forms import clean_text, validation_error
4+
5+
6+
@pytest.mark.parametrize(
7+
("raw", "expected"),
8+
[
9+
(None, ""),
10+
(" Vancouver,\t\n Canada ", "Vancouver, Canada"),
11+
("Dan", "Dan"), # fullwidth letters
12+
("Da​n", "Dan"), # zero-width space
13+
("‮evil", "evil"), # right-to-left override
14+
("bell\x07", "bell"),
15+
("Zoë", "Zoë"),
16+
("José", "José"), # decomposed e + accent becomes one character
17+
("👩‍💻 coder", "👩‍💻 coder"),
18+
("北京, 中国", "北京, 中国"),
19+
],
20+
)
21+
def test_clean_text(raw, expected):
22+
assert clean_text(raw) == expected
23+
24+
25+
@pytest.mark.parametrize(
26+
"nickname",
27+
[None, "Ada", "Zoë", "李雷", "Đặng Thị", "👩‍💻 Ada", "@ada_codes"],
28+
)
29+
def test_reasonable_nicknames_are_accepted(nickname):
30+
assert validation_error("Berlin, Germany", nickname) is None
31+
32+
33+
@pytest.mark.parametrize(
34+
("nickname", "message"),
35+
[
36+
("n" * 51, "at most 50 characters"),
37+
("http://spam.example", "can't contain links"),
38+
("www.spam.example", "can't contain links"),
39+
("buy-pills.com", "can't contain links"),
40+
("me@example.org", "email address"),
41+
("Z͓͔͑͒a", "stacked accent marks"),
42+
("!!!***", "at least one letter or number"),
43+
("🔥🔥🔥", "at least one letter or number"),
44+
],
45+
)
46+
def test_bad_nicknames_are_rejected(nickname, message):
47+
error = validation_error("Berlin, Germany", nickname)
48+
49+
assert error is not None
50+
assert error.startswith("Nickname")
51+
assert message in error
52+
53+
54+
def test_bad_locations_are_rejected():
55+
assert "Location can't contain links" in validation_error(
56+
"visit https://spam.example", None
57+
)

‎tests/test_views.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,9 @@ def test_geocoder_down(app, client, geocode):
141141
("data", "message"),
142142
[
143143
({"location": ""}, "Please enter a city and country"),
144-
({"location": "x" * 201}, "That location is too long"),
144+
({"location": "x" * 201}, "Location can be at most 200"),
145+
({"location": "Oslo", "nickname": "see www.spam.example"}, "links"),
146+
({"location": "Oslo", "nickname": "a@b.example"}, "email address"),
145147
({"location": "Oslo", "nickname": "n" * 51}, "at most 50"),
146148
],
147149
)

0 commit comments

Comments
 (0)