Forgot Password

This seems like a good opportunity to add a feature on the login page which gives a user an option to reset their password if they’ve forgotten it. It uses the same tokens as email verification: we email the user a link containing a token, and the link takes them to a form for choosing a new password.

For example, add the following link in the login.html template, below the form:

web/templates/login.htmljinja
                <p><a href="/auth/password/reset">Forgotten your password?</a> &middot; <a href="/auth/register">Register</a></p>

Add a view to render the password reset page:

web/views/auth_views.pypython
@router.get('/auth/password/reset', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def password_reset_get_view(*, request: Request):

    context = {
        "page": "reset"
    }

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

And the corresponding template:

web/templates/reset.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>Reset Password</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>Enter your email address to receive a password reset link:</p>
                <form action="/auth/password/reset" method="post">
                    <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" autocomplete="email" required>
                        </div>
                    </div>
                    <br>
                    <button type="submit" class="btn btn-default">Send Link</button>
                </form>
            </div>
        </div>
    </div>

{% endblock %}

The form submits a POST request to /auth/password/reset. If the email address belongs to an active user, the view creates a token and emails the link, valid for 30 minutes:

web/views/auth_views.pypython
RESET_LINK_LIFETIME = datetime.timedelta(minutes=30)
web/views/auth_views.pypython
@router.post('/auth/password/reset', response_class=HTMLResponse)
def password_reset_post_view(*,
                             request: Request,
                             background_tasks: BackgroundTasks,
                             email: EmailStr = Form(...),
                             session: Session = Depends(get_session_db)):
    user = get_user_by_email_api(email, session)
    if user and user.is_active:
        token = create_auth_token_api(user.id, "reset_password", RESET_LINK_LIFETIME, session)
        body = (f"Hi {user.first_name},\n\n"
                f"You can choose a new password here: {settings.CONF_MAIN_DOMAIN}/auth/password/reset/{token}\n\n"
                f"The link expires in 30 minutes. If you didn't ask to reset your password, you can ignore this email.")
        background_tasks.add_task(send_email_or_500, subject="Reset your password", body=body, recipients=[email])

    # The same answer whether or not the address has an account, so this can't be used to find out
    return message_page(request, "Reset Password",
                        "If that email address has an account, we've sent it a link to reset the password.")

Notice the response is the same whether or not the address has an account. Otherwise anyone could type in email addresses to find out who has an account.

Choosing a new password#

The link in the email leads to this view, which checks the token and shows a form for the new password:

web/views/auth_views.pypython
@router.get('/auth/password/reset/{token}', response_class=HTMLResponse)
def password_reset_form_view(*, token: str, request: Request, session: Session = Depends(get_session_db)):
    if not check_auth_token_api(token, "reset_password", session):
        return message_page(request, "Oops", "That password reset link is invalid or has expired.",
                            status.HTTP_400_BAD_REQUEST)

    context = {
        "page": "reset",
        "token": token
    }

    return templates.TemplateResponse(request, 'reset_form.html', {'context': context})
web/templates/reset_form.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>Reset Password</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>Choose a new password:</p>
                <form action="/auth/password/reset/{{ context.token }}" method="post">
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>New Password</label>
                            <input type="password" class="form-control" placeholder="New password (at least 8 characters)" id="password" name="password" minlength="8" autocomplete="new-password" required>
                        </div>
                    </div>
                    <br>
                    <button type="submit" class="btn btn-default">Change Password</button>
                </form>
                {% if context.error_message %}<p><strong>{{ context.error_message }}</strong></p>{% endif %}
            </div>
        </div>
    </div>

{% endblock %}

The form posts back to the same URL, token included. The token isn’t used up yet, so reloading the page still works. When the form is submitted, the token is checked again, used up, and the password changed:

web/views/auth_views.pypython
@router.post('/auth/password/reset/{token}', response_class=HTMLResponse)
def password_reset_update_view(*,
                               token: str,
                               request: Request,
                               password: str = Form(...),
                               session: Session = Depends(get_session_db)):
    if len(password) < MIN_PASSWORD_LENGTH:
        context = {
            "page": "reset",
            "token": token,
            "error_message": f"Please choose a password of at least {MIN_PASSWORD_LENGTH} characters."
        }
        return templates.TemplateResponse(request, 'reset_form.html', {'context': context},
                                          status_code=status.HTTP_400_BAD_REQUEST)

    user = check_auth_token_api(token, "reset_password", session, use=True)
    if not user:
        return message_page(request, "Oops", "That password reset link is invalid or has expired.",
                            status.HTTP_400_BAD_REQUEST)
    set_user_password_api(user, password, session)
    return message_page(request, "Password changed", "Your password has been changed. You can now log in.")

It uses a small function in api/auth_apis.py to hash and store the new password:

api/auth_apis.pypython
def set_user_password_api(user: User, password: str, session: Session) -> None:
    user.hashed_password = get_password_hash_api(password)
    session.add(user)
    session.commit()
The token is the proof

An earlier version of this guide put the user’s id in a read-only form field, and had a separate /auth/password/update view that changed the password for whatever id it was sent, without checking a token at all. Anyone could have changed anyone’s password by sending a user id. “Read-only” only stops the field being edited in the browser: the request can contain anything. Here the token, which only arrived in the user’s email, is the only thing that identifies the user, and it’s checked when the password is changed, not just when the form is shown.

Testing#

The example code includes test_registration.py, which goes through registering, activating and logging in (reading the link from the email printed in dev mode), duplicate emails, short passwords and the CAPTCHA, and the whole password reset flow: that only a hash is stored, that links only work once, that unknown email addresses aren’t revealed, and that a password can’t be changed without a valid token.