Registration Form

The user registration form will include a CAPTCHA, and we’ve already implemented that functionality. So, using login.html and contact_form.html as examples, add the following register.html template:

web/templates/register.htmljinja
{% extends "_base.html" %}

{% block content %}

    <!-- Page Header -->
    <header class="intro-header" style="background-image: url('/static/img/about-bg.jpg')">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="page-heading">
                        <h1>Register</h1>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <p>Use the form to register:</p>
                <form action="/auth/register" method="post">
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>First Name</label>
                            <input type="text" class="form-control" placeholder="First Name" id="first_name" name="first_name" value="{{ context.first_name or '' }}" autocomplete="given-name" required>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Last Name</label>
                            <input type="text" class="form-control" placeholder="Last Name" id="last_name" name="last_name" value="{{ context.last_name or '' }}" autocomplete="family-name" required>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Email</label>
                            <input type="email" class="form-control" placeholder="Email" id="email" name="email" value="{{ context.email or '' }}" autocomplete="email" required>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Password</label>
                            <input type="password" class="form-control" placeholder="Password (at least 8 characters)" id="password" name="password" minlength="8" autocomplete="new-password" required>
                        </div>
                    </div>
                    <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" placeholder="CAPTCHA (enter the five characters shown below)" id="captcha_text" name="captcha_text" autocomplete="off" 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>
                    <button type="submit" class="btn btn-default">Register</button>
                </form>
                {% if context.error_message %}<p><strong>{{ context.error_message }}</strong></p>{% endif %}
            </div>
        </div>
    </div>

{% endblock %}

The minlength="8" and autocomplete="new-password" attributes let the browser check the length and offer to generate a strong password. The view checks the length too, since a browser check is easily bypassed.

Several pages in this section only need to show a short message, such as “check your email”, so rather than a template for each one, add a general-purpose template:

web/templates/auth_message.htmljinja
{% extends "_base.html" %}

{% block content %}

    <!-- Page Header -->
    <header class="intro-header" style="background-image: url('/static/img/about-bg.jpg')">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                    <div class="page-heading">
                        <h1>{{ context.title }}</h1>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <p>{{ context.message }}</p>
            </div>
        </div>
    </div>

{% endblock %}

And a small helper at the top of auth_views.py that renders it:

web/views/auth_views.pypython
def message_page(request: Request, title: str, message: str, status_code: int = status.HTTP_200_OK):
    context = {"page": "message", "title": title, "message": message}
    return templates.TemplateResponse(request, 'auth_message.html', {'context': context}, status_code=status_code)

You’ll need to import create_captcha and verify_captcha, plus a few other things used below:

web/views/auth_views.pypython
import uuid  # NEW

from fastapi import APIRouter, Depends, Form, Request, status
from pydantic import EmailStr  # NEW

from api.auth_apis import (AUTH_COOKIE, authenticate_user_api, create_access_token_api,
                           get_password_hash_api, is_user, set_auth_cookie)  # UPDATED
from api.captcha_apis import create_captcha, verify_captcha  # NEW
from db.schemas.user_schemas import User  # NEW
web/views/auth_views.pypython
MIN_PASSWORD_LENGTH = 8

Add the following view to render the register form:

web/views/auth_views.pypython
@router.get('/auth/register', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def register_get_view(*, request: Request, session: Session = Depends(get_session_db)):

    if is_user(request, session):
        return RedirectResponse(url='/', status_code=status.HTTP_303_SEE_OTHER)

    context = {
        "page": "register",
        "captcha_id": create_captcha(session).id,
    }

    return templates.TemplateResponse(request, 'register.html', {'context': context})

We’ll build the registration flow up in phases. For now, the POST function checks the CAPTCHA and the password, and creates the user:

web/views/auth_views.pypython
@router.post('/auth/register', response_class=HTMLResponse)
def register_post_view(*,
                       request: Request,
                       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."

    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()

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

The checks run in order, and the first one that fails sends the user back to the form, keeping what they typed, with an error message and a new CAPTCHA, the same pattern as the contact form.

New users are created with is_active=False. They can’t log in until they’ve proved the email address is theirs, by following a link sent to it, which is added in the Email Verification section. Until then, you can activate a test account in the database. Registered users are not is_author or is_member: membership is something users pay for, in the Payments section.

The view creates the User directly, rather than through create_user_api, because UserIn lets the caller choose flags like is_superuser, which a public registration form must never do.

Finally, add a page telling the user what happens next, using the message template:

web/views/auth_views.pypython
@router.get('/auth/register/verify', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def register_verify_view(*, request: Request):
    return message_page(request, "Registration", "Please check your email for an activation link.")

And a Register link to the navigation in _base.html, for visitors who aren’t logged in, after the Login link:

web/templates/_base.htmljinja
                    <li{% if context.page == 'register' %} class="active"{% endif %}>
                        <a href="/auth/register">Register</a>
                    </li>