Add a honeypot field to forms

This commit is contained in:
Yannik Rödel 2022-06-15 16:17:00 +02:00
parent 8711307216
commit 929edd3711
2 changed files with 25 additions and 2 deletions

View file

@ -23,6 +23,8 @@ def fail(status: str, reason: str) -> None:
exit(0)
HONEYPOT_FIELD_NAME = "addressline1"
SITE_DIRECTORY = os.environ.get("SITE_DIRECTORY", "")
request_uri = os.environ.get("REQUEST_URI", "").lower().rstrip("/")
serializer = itsdangerous.URLSafeSerializer("secret key", "salt")
@ -64,14 +66,23 @@ match os.environ.get("REQUEST_METHOD", "").upper():
with open(f"{SITE_DIRECTORY}/{request_uri.strip('/')}/index.html", "r") as template:
for line in template.readlines():
print(line)
# This is a very rudimentary check to ensure that we actually
# place the token *inside* the form. It assumes that there is
# a) only one form on the site and
# b) the <form> tag doesn't end on the same line.
if "<form" in line.lower():
if "</form" in line.lower():
print(f'<input type="hidden" name="csrftoken" value="{csrf_token}" />')
print(f'<label class="form-input">')
print(f'<span>Bitte lasse dieses Feld leer:</span>')
print(f'<input type="text" name="{HONEYPOT_FIELD_NAME}" value="" placeholder="Hier nichts eingeben." />')
print(f'</label>')
print(f'<script type="text/javascript">')
print(f'document.querySelector("input[name={HONEYPOT_FIELD_NAME}]").parentNode.classList.add("isolated")')
print(f'</script>')
print(line)
exit(0)
case "POST":
@ -126,6 +137,11 @@ if not hmac.compare_digest(csrf_token, given_csrf_token):
fail("400 Bad Request", f"Invalid CSRF token")
# If the honeypot field was not empty, back off.
if get_form_value(HONEYPOT_FIELD_NAME, ""):
fail("200 OK", f"Invalid value for field: {HONEYPOT_FIELD_NAME}")
# Extract all the actually provided form data. This is different from form to
# form (see the match block below).
contact_name = get_form_value("contactname")

View file

@ -61,6 +61,13 @@
.form-input {
@extend %form-item;
&.isolated {
position: absolute;
top: -100%;
opacity: 0;
pointer-events: none;
}
> :first-child {
@extend %form-label;
flex-grow: 1;