Password Reset

It’s useful for users to be able to change their password while they’re logged in. The view uses set_user_password_api and verify_password_api from api/auth_apis.py, and the same minimum length as registration:

web/views/profile_views.pypython
@router.post('/profile/password', response_class=HTMLResponse)
def profile_password_view(*,
                          request: Request,
                          current_password: str = Form(...),
                          new_password: str = Form(...),
                          session: Session = Depends(get_session_db)):
    current_user = is_user(request, session)
    if current_user is None:
        return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)

    # Ask for the current password, so someone using an unattended, logged-in
    # browser can't lock the owner out of their account
    if not verify_password_api(current_password, current_user.hashed_password):
        return profile_page(request, current_user, error="Your current password wasn't right.",
                            status_code=status.HTTP_400_BAD_REQUEST)
    if len(new_password) < MIN_PASSWORD_LENGTH:
        return profile_page(request, current_user,
                            error=f"Please choose a password of at least {MIN_PASSWORD_LENGTH} characters.",
                            status_code=status.HTTP_400_BAD_REQUEST)

    set_user_password_api(current_user, new_password, session)
    return profile_page(request, current_user, message="Your password has been changed.")

The form asks for the current password as well as the new one. Being logged in only proves someone has the login cookie: they might be using a computer the owner left unattended. Asking for the current password stops them taking over the account by changing it.

autocomplete="current-password" and autocomplete="new-password" in the form tell password managers which field is which, so they can fill in the current password and offer to generate the new one.

note

Changing the password doesn’t log out other browsers where the user is logged in: their JWTs stay valid until they expire, after CONF_AUTH_EXPIRE_MINUTES. To log everyone out on a password change, you could store a “token version” number on the user, put it in the JWT, and reject tokens with an old number.