Email Verification

To verify an email address, we send it a link containing a secret token. Following the link proves the user can read email sent to that address, and activates the account. The same idea works for resetting forgotten passwords, in the next section, so it’s worth building it once, properly.

Tokens#

The token is the only thing standing between an attacker and someone else’s account, so:

  • It must be impossible to guess. secrets.token_urlsafe(32) gives 32 random bytes (256 bits), as URL-safe text.
  • It must only work once, and only for a limited time.
  • Only a hash of it is stored, like a password. If someone gets a copy of the database, they still can’t use the links. A fast hash, SHA-256, is fine here: unlike passwords, the tokens are long and random, so there’s nothing to guess.

Add a table for the tokens to user_schemas.py. purpose says what a token is for, so a verification token can’t be used to reset a password:

db/schemas/user_schemas.pypython
# Single-use tokens for email verification and password reset links
class AuthToken(SQLModel, table=True):
    id: uuid.UUID = Field(
        default_factory=uuid.uuid4,
        primary_key=True)
    token_hash: str = Field(unique=True, index=True)
    purpose: str  # "verify_email" or "reset_password"
    user_id: uuid.UUID = Field(foreign_key="user.id", ondelete="CASCADE")
    expires: datetime.datetime

ondelete="CASCADE" deletes a user’s tokens along with the user.

Add it to alembic/env.py, and create the migration:

alembic/env.pypython
from db.schemas.user_schemas import AuthToken, User  # UPDATED
alembic revision --autogenerate -m "added auth tokens"
alembic upgrade head

Then add functions to api/auth_apis.py to create and check tokens:

api/auth_apis.pypython
import datetime
import hashlib  # NEW
import secrets  # NEW
import uuid
api/auth_apis.pypython
from sqlmodel import Session, delete, select  # UPDATED
api/auth_apis.pypython
from db.schemas.user_schemas import AuthToken, User, UserIn, UserOut  # UPDATED
api/auth_apis.pypython
# Single-use tokens for links sent by email
def hash_token(token: str) -> str:
    return hashlib.sha256(token.encode()).hexdigest()

def create_auth_token_api(user_id: uuid.UUID, purpose: str, lifetime: datetime.timedelta,
                          session: Session) -> str:
    """Create a token for a link, replacing any earlier one. Returns the token itself;
    only its hash is stored, so the database alone can't be used to follow the link."""
    now = datetime.datetime.now(datetime.UTC)
    session.exec(delete(AuthToken).where(AuthToken.expires < now))
    session.exec(delete(AuthToken).where(AuthToken.user_id == user_id, AuthToken.purpose == purpose))
    token = secrets.token_urlsafe(32)
    session.add(AuthToken(token_hash=hash_token(token), purpose=purpose, user_id=user_id, expires=now + lifetime))
    session.commit()
    return token

def check_auth_token_api(token: str, purpose: str, session: Session, use: bool = False) -> User | None:
    """The user a valid, unexpired token belongs to, or None. With use=True the token is deleted."""
    query = select(AuthToken).where(AuthToken.token_hash == hash_token(token), AuthToken.purpose == purpose)
    auth_token = session.exec(query).first()
    if not auth_token or auth_token.expires < datetime.datetime.now(datetime.UTC):
        return None
    user = session.get(User, auth_token.user_id)
    if use:
        session.delete(auth_token)
        session.commit()
    return user
  • create_auth_token_api first tidies up: it deletes expired tokens, and any earlier token the user had for the same purpose, so only the latest link works. Then it stores the hash, and returns the token itself, to put in the link.
  • check_auth_token_api finds the token by its hash and purpose, and checks it hasn’t expired. With use=True it also deletes it, so the link can’t be used again.

Update register_post_view to create a token after the user is created, and email the link to the new user. You’ll need some more imports:

web/views/auth_views.pypython
import datetime  # NEW
import uuid

from fastapi import APIRouter, BackgroundTasks, Depends, Form, Request, status  # UPDATED
web/views/auth_views.pypython
from api.auth_apis import (AUTH_COOKIE, authenticate_user_api, check_auth_token_api, create_access_token_api,
                           create_auth_token_api, get_user_by_email_api, get_password_hash_api, is_user,
                           set_auth_cookie, set_user_password_api)  # UPDATED
from config.settings import settings  # NEW
from mail.sendmail import send_email_or_500  # NEW
web/views/auth_views.pypython
VERIFY_LINK_LIFETIME = datetime.timedelta(hours=24)

Here is the complete register_post_view:

web/views/auth_views.pypython
@router.post('/auth/register', response_class=HTMLResponse)
def register_post_view(*,
                       request: Request,
                       background_tasks: BackgroundTasks,
                       first_name: str = Form(...),
                       last_name: str = Form(...),
                       email: EmailStr = Form(...),
                       password: str = Form(...),
                       captcha_id: uuid.UUID = Form(...),
                       captcha_text: str = Form(...),
                       session: Session = Depends(get_session_db)):

    error_message = None
    if not verify_captcha(id=captcha_id, text=captcha_text, session=session):
        error_message = "The CAPTCHA text didn't match, please try again."
    elif len(password) < MIN_PASSWORD_LENGTH:
        error_message = f"Please choose a password of at least {MIN_PASSWORD_LENGTH} characters."
    elif get_user_by_email_api(email, session):
        error_message = "That email address is already registered. Have you forgotten your password?"

    if error_message:
        context = {
            "page": "register",
            "first_name": first_name,
            "last_name": last_name,
            "email": email,
            "captcha_id": create_captcha(session).id,
            "error_message": error_message,
        }
        return templates.TemplateResponse(request, 'register.html', {'context': context},
                                          status_code=status.HTTP_400_BAD_REQUEST)

    # New accounts stay inactive until the email address is verified
    new_user = User(first_name=first_name, last_name=last_name, email=email, username=email,
                    profile_image="/static/img/profile.jpg", is_active=False,
                    hashed_password=get_password_hash_api(password))
    session.add(new_user)
    session.commit()

    token = create_auth_token_api(new_user.id, "verify_email", VERIFY_LINK_LIFETIME, session)
    body = (f"Hi {first_name},\n\n"
            f"Please activate your account here: {settings.CONF_MAIN_DOMAIN}/auth/verify/{token}\n\n"
            f"The link expires in 24 hours. Thank you for registering at {settings.CONF_MAIN_DOMAIN}.")
    background_tasks.add_task(send_email_or_500, subject="Activate your account", body=body, recipients=[email])

    return RedirectResponse('/auth/register/verify', status_code=status.HTTP_303_SEE_OTHER)

The email isn’t sent straight away. background_tasks.add_task() asks FastAPI to call send_email_or_500 after the response has been sent, so the user doesn’t wait for the mail server. This is the example the FastAPI documentation uses for background tasks. FastAPI runs background tasks that are plain functions, like send_email_or_500, in its thread pool. If sending fails, the error is written to the application’s log rather than shown to the user.

The email goes to the address the user registered with: recipients=[email]. The link uses CONF_MAIN_DOMAIN, so set that to your real domain when you deploy.

The verification link is valid for 24 hours, long enough for anyone who doesn’t check their email often.

Add a view for the link, which activates the account if the token is valid:

web/views/auth_views.pypython
@router.get('/auth/verify/{token}', response_class=HTMLResponse)
def verify_view(*, token: str, request: Request, session: Session = Depends(get_session_db)):
    user = check_auth_token_api(token, "verify_email", session, use=True)
    if not user:
        return message_page(request, "Oops", "That activation link is invalid or has expired.",
                            status.HTTP_400_BAD_REQUEST)
    user.is_active = True
    session.add(user)
    session.commit()
    return message_page(request, "Account activated", "Thank you, your account is active. You can now log in.")

use=True means a link can only be followed once. An invalid, expired or already used link shows a message, rather than an error.

All being well, if you register a new user via the registration form (with CONF_MAIL_DEV_MODE on), you’ll see the email in the console output, with the activation link. Following that link should activate the account, ready to log in:

--- Email (dev mode, not sent) ---
To: jane@example.com
Subject: Activate your account

Hi Jane,

Please activate your account here: https://localhost/auth/verify/5mK3nqA0b7Zp2w1rXJ8f0YQzS4uT6vH9cE2dL1oPgRk

The link expires in 24 hours. Thank you for registering at https://localhost.
----------------------------------

Finally, an account that hasn’t been activated can’t log in. Rather than the usual “Incorrect username or password”, which would be confusing, the login view now tells the user to activate their account, but only once their password has proved who they are:

web/views/auth_views.pypython
    user = authenticate_user_api(username, password, session)
    if not user or not user.is_active:
        # Only say the account isn't activated once the password has proved who they are
        msg = "Please activate your account using the link we emailed you." if user \
            else "Incorrect username or password"

authenticate_user_api only returns a user if the password was right, so someone guessing can’t use this to discover unactivated accounts.