CAPTCHA
NotesIt’s great to have a working contact form, but there is still a risk that robots could spam the web form. It’s a nice touch to include a CAPTCHA to prevent that from happening.
CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart.” It is a security mechanism used on websites and online services to distinguish between automated bots (computer programs) and human users.
The steps that follow should start to become familiar: creating schemas, the APIs and then adding or updating the views.
There is a pattern called Model View Controller (MVC). Broadly speaking, that is what we’re essentially doing here: the schemas are our database Models, the views are our views, and the APIs are essentially the controllers.
Remember, I’m deliberately putting logic into the APIs because it lays the foundation for breaking the application into microservices. It should be easy to see how the APIs could be broken off into their own application and used by the presentation layer application as external APIs.
Install captcha using pip and remember to freeze this to the requirements files.
pip install captchaAdd it to the non_ver_reqs.txt file:
fastapi[standard]
pydantic-settings
pytest
sqlmodel
alembic
markdown
nh3
pillow
captchapip freeze > requirements.txtHow it works#
A CAPTCHA is only as good as the secret it protects, so it’s worth getting the design right:
- When the form is shown, a random five-character answer is generated and stored in the database with a random UUID as its
id. - The page includes that
idtwice: in a hidden form field, and in the URL of the image,/captcha/<id>.png. The image is drawn on the fly from the stored answer. The answer itself never appears in the page, the image URL or a file name. - When the form is submitted, the answer typed in is checked against the CAPTCHA with that
id, and only that one. The record is deleted straight away, whether the answer was right or wrong, so each CAPTCHA can only be tried once, and CAPTCHAs older than ten minutes are rejected.
An earlier version of this guide named the image files after their answer (for example pxfcb_2023_03_10.png), so a bot could read the answer from the page without looking at the image at all. It also accepted any unexpired answer, not just the one on the form. If you built that version, it’s worth updating.
Generating images on request also means there are no image files to store, mount or clean up.
Schema#
Create a new database schema for storing CAPTCHA records:
import uuid
import datetime
from sqlmodel import SQLModel, Field
class Captcha(SQLModel, table=True):
id: uuid.UUID = Field(
default_factory=uuid.uuid4,
primary_key=True)
text: str = Field(max_length=10)
created: datetime.datetime = Field(
default_factory=lambda: datetime.datetime.now(datetime.UTC))This is only ever used internally, so unlike the blog posts it needs no separate input and output schemas.
With this new schema added, you’ll have to let Alembic know it now exists:
from db.schemas.blog_schemas import BlogPost
from db.schemas.captcha_schemas import Captcha # NEWAnd create a new revision:
alembic revision --autogenerate -m "added captcha table"def upgrade() -> None:
"""Upgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('captcha',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('text', sqlmodel.sql.sqltypes.AutoString(length=10), nullable=False),
sa.Column('created', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###alembic upgrade headCreating and checking CAPTCHAs#
Create a new Python file for the CAPTCHA functions, and the route that serves the images:
import datetime
import secrets
import string
import uuid
from captcha.image import ImageCaptcha
from fastapi import APIRouter, Depends, HTTPException, Response, status
from sqlmodel import Session, delete
from db.db import get_session_db
from db.schemas.captcha_schemas import Captcha
router = APIRouter()
CAPTCHA_LENGTH = 5
CAPTCHA_LIFETIME = datetime.timedelta(minutes=10)
# No 0/o or 1/l/i: they're too easy to confuse in a distorted image
CAPTCHA_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789"
# Functions
def create_captcha(session: Session) -> Captcha:
"""Create and store a new CAPTCHA, removing any that have expired."""
expired_before = datetime.datetime.now(datetime.UTC) - CAPTCHA_LIFETIME
session.exec(delete(Captcha).where(Captcha.created < expired_before))
text = ''.join(secrets.choice(CAPTCHA_ALPHABET) for _ in range(CAPTCHA_LENGTH))
captcha = Captcha(text=text)
session.add(captcha)
session.commit()
session.refresh(captcha)
return captcha
def verify_captcha(id: uuid.UUID, text: str, session: Session) -> bool:
"""Check an answer. Each CAPTCHA can only be tried once, right or wrong."""
captcha = session.get(Captcha, id)
if not captcha:
return False
session.delete(captcha)
session.commit()
not_expired = datetime.datetime.now(datetime.UTC) - captcha.created < CAPTCHA_LIFETIME
return not_expired and secrets.compare_digest(captcha.text, text.strip().lower())
# Routes
@router.get('/captcha/{id}.png', include_in_schema=False)
def captcha_image(id: uuid.UUID, session: Session = Depends(get_session_db)) -> Response:
captcha = session.get(Captcha, id)
if not captcha:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
image = ImageCaptcha(width=280, height=90).generate(captcha.text)
return Response(content=image.getvalue(), media_type="image/png",
headers={"Cache-Control": "no-store"})Stepping through it:
create_captcha()first deletes any CAPTCHAs that have expired, so the table never grows. Then it picks five characters withsecrets.choice(). Thesecretsmodule is designed for security purposes like this, while therandommodule is predictable enough that its output can be guessed. The alphabet leaves out characters that are easily confused, such as0ando.verify_captcha()looks the CAPTCHA up byid, deletes it, and then checks it hasn’t expired and the answer matches.text.strip().lower()ignores capitals and stray spaces, andsecrets.compare_digest()compares in constant time, so the time taken doesn’t reveal how much of the answer was right.captcha_image()draws the image for a CAPTCHA withImageCaptcha, entirely in memory, and returns it as a PNG.Cache-Control: no-storestops browsers keeping old images.include_in_schema=Falseleaves it out of the Swagger docs, since it’s part of the website rather than an API.
The image route is part of the website, so include its router in main.py unconditionally, not inside the CONF_ENABLE_APIS check:
from api import health_api, blog_apis, captcha_apis # UPDATED main_app.include_router(contact_view.router, tags=["web_views"])
main_app.include_router(captcha_apis.router, tags=["web_views"]) # NEWUpdating the contact form#
Update the contact view so the GET function creates a CAPTCHA, and the POST function checks it:
import uuid
from fastapi import APIRouter, Depends, Form, Request, status
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pydantic import EmailStr
from sqlmodel import Session
from api.captcha_apis import create_captcha, verify_captcha
from config.settings import settings
from db.db import get_session_db
from mail.sendmail import send_email_or_500
router = APIRouter()
templates = Jinja2Templates('web/templates')
# Contact Form
@router.get('/contact', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def contact_get_view(*, request: Request, session: Session = Depends(get_session_db)):
context = {
"page": "contact",
"captcha_id": create_captcha(session).id,
}
return templates.TemplateResponse(request, 'contact_form.html', {'context': context})
@router.post('/contact', response_class=HTMLResponse)
def contact_post_view(*,
request: Request,
name: str = Form(...),
email: EmailStr = Form(...),
message: str = Form(...),
captcha_id: uuid.UUID = Form(...),
captcha_text: str = Form(...),
session: Session = Depends(get_session_db)):
if not verify_captcha(id=captcha_id, text=captcha_text, session=session):
# Back to the form, keeping what was typed, with a fresh CAPTCHA
context = {
"page": "contact",
"name": name,
"email": email,
"message": message,
"captcha_id": create_captcha(session).id,
"error_message": "The CAPTCHA text didn't match, please try again.",
}
return templates.TemplateResponse(request, 'contact_form.html', {'context': context},
status_code=status.HTTP_400_BAD_REQUEST)
name = " ".join(name.split()) # no line breaks: the name goes in the email's subject line
body = (f"You have a message from {name} <{email}>.\n\n"
f"{message}\n\n"
f"Sent from the contact form at {settings.CONF_MAIN_DOMAIN}")
send_email_or_500(subject=f"Contact form message from {name}",
body=body,
recipients=[settings.CONF_MAIL_CONTACT_TO],
reply_to=[email])
context = {
"page": "contact"
}
return templates.TemplateResponse(request, 'message_sent.html', {'context': context})If the CAPTCHA doesn’t match, the user is returned to the contact form, with everything they typed filled back in, a fresh CAPTCHA and an error_message. That way they don’t lose their message. The status is 400 Bad Request, which tells the browser (and any bot) that the submission wasn’t accepted.
With the view now passing a captcha_id to the template, update the contact form to include the CAPTCHA field, the hidden id and the image, after the message field:
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>CAPTCHA</label>
<input type="text" class="form-control" autocomplete="off"
placeholder="CAPTCHA (enter the five characters shown below)"
id="captcha_text" name="captcha_text" required>
<input type="hidden" name="captcha_id" value="{{ context.captcha_id }}">
</div>
</div>
<br>
<img src="/captcha/{{ context.captcha_id }}.png" alt="CAPTCHA image" width="280" height="90">
<br><br>And below the form, show the error message, if there is one:
{% if context.error_message %}<p><strong>{{ context.error_message }}</strong></p>{% endif %}You should now be presented with a random CAPTCHA image on the contact form:
Testing#
The example code includes test_contact.py, which checks that the answer never appears in the page, that a wrong answer returns the form with the values filled in and a new CAPTCHA, that a right answer sends the email (in dev mode, so it’s printed rather than sent), and that a CAPTCHA can’t be used twice. To read the answer from the database, conftest.py gained a session fixture that shares the test database with the client.