Confirm

The confirm function is a crucial component of the user authentication process in a web application, specifically within the auth module. It serves as a URL handler that processes the confirmation link clicked by a new user. This function is responsible for verifying the validity of the confirmation token and updating the user's confirmation status in the database.

Confirmation Process

Sending Confirmation Email

The process begins with the send_confirmation_email() function, which is responsible for sending an email to the user with a confirmation link. This function performs the following steps:

  1. Generate Confirmation Token: It calls the confirmation_token() method of the User model to create a unique token with an expiration timeout.
  2. Construct Confirmation URL: It uses the url_for() function to build a URL that points to the auth_bp.confirm URL handler. The _external=True parameter ensures that a full URL is generated, suitable for email clients.
  3. Send Email: The function constructs an email with the confirmation URL and sends it to the user's email address.
def send_confirmation_email(user):
    confirmation_token = user.confirmation_token()
    confirmation_url = url_for(
        "auth_bp.confirm",
        confirmation_token=confirmation_token,
        _external=True
    )
    timeout = current_app.config.get("CONFIRMATION_LINK_TIMEOUT")
    to = user.email
    subject = "Confirm Your Email"
    contents = (
        f"""Dear {user.first_name},<br /><br />
        Welcome to MyBlog, please click the link to
        confirm your email within {timeout} hours:
        {confirmation_url}<br /><br />
        Thank you!
        """
    )
    send_mail(to=to, subject=subject, contents=contents)

Generating Confirmation Token

The confirmation_token() method in the User model generates a unique token for each user. It uses the URLSafeTimedSerializer function, which is initialized with the Flask SECRET_KEY and includes a timestamp. This ensures that the token is both unique and time-sensitive.

def confirmation_token(self):
    serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
    return serializer.dumps({"confirm": self.user_uid})

Handling Confirmation Link

When a user clicks the confirmation link in their email, the confirm function is triggered. This function performs several checks and updates:

  1. Check User Confirmation Status: If the user is already confirmed, they are redirected to the home page.
  2. Validate Confirmation Token: The function attempts to confirm the token using the confirm_token() method. If successful, it updates the user's confirmation status in the database.
  3. Handle Exceptions: If the token is invalid or expired, an exception is logged, and the user is redirected to the resend confirmation page.
@auth_bp.get("/confirm/<confirmation_token>")
@login_required
def confirm(confirmation_token):
    if current_user.confirmed:
        return redirect(url_for("intro_bp.home"))
    try:
        if current_user.confirm_token(confirmation_token):
            with db_session_manager() as db_session:
                current_user.confirmation = True
                db_session.add(current_user)
                db_session.commit()
                flash("Thank you for confirming your account")
    except Exception as e:
        logger.exception(e)
        flash(e.message)
        return redirect(url_for("auth_bp.resend_confirmation"))
    return redirect(url_for("intro_bp.home"))

Confirming the Token

The confirm_token() method is responsible for verifying the token's validity. It uses the same serializer as the confirmation_token() method to deserialize the token and checks if the token's data matches the user's unique identifier. If the token is valid, the user's confirmation status is updated in the database.

def confirm_token(self, token):
    serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
    with db_session_manager() as session:
        confirmation_link_timeout = current_app.config.get("CONFIRMATION_LINK_TIMEOUT")
        timeout = confirmation_link_timeout * 60 * 1000
        try:
            data = serializer.loads(token, max_age=timeout)
            if data.get("confirm") != self.user_uid:
                return False
            self.confirmed = True
            session.add(self)
            return True
        except (SignatureExpired, BadSignature) as e:
            return False

In summary, the confirm function and its associated methods and handlers form a comprehensive system for managing user email confirmations, ensuring that only valid and timely confirmations are processed.