How to Guide Verify User Email Address with Python and Firebase

In this tutorial, we are going to discuss and walk through how we can implement Firebase’s email verification API to verify the email address of our app users.

TLDR: Clone this GitHub repo.

Prerequisites

We will need a Google account and a Firebase project set up to implement the email verification.

You can follow that tutorial to gain basic understanding of how Firebase can be integrated with your application back end.

Besides walking through Firebase project setup, the tutorial also covers user management, which includes creating a user, updating the user’s details, setting a user’s password, authenticating a user with email and password, and deleting a user.

Please clone this GitHub repository before moving on to the next section.

Send Email Verification Link

Alright, let’s get to the first part of this tutorial, which is to send an email to the user containing the email verification link.

The API to send an email verification link is part of Firebase Auth REST API. It is a POST endpoint that accepts a request body containing requestType, whos value should always be "VERIFY_EMAIL" and idToken, which is the Firebase ID token we get when a user is authenticated.

So, let’s create a new user, set a password and authenticate so that we can obtain the Firebase ID token. All of the steps are covered in the tutorial mentioned earlier.

Go ahead and create a user with an email address that you have access to so that you can receive the email verification link later on.

This is what the steps will look like if you follow the tutorial referenced above.

~/demo/python-admin-sdk-demo ❯ python create_user.py --email your.email@yourdomain.com --user-id 12345

Firebase successfully created a new user with email - your.email@yourdomain.com and user id - 12345

~/demo/python-admin-sdk-demo ❯ python set_password.py --user-id 12345 --password whateverpasswordyouwanttouse

Firebase has updated the password for user with user id - 12345

~/demo/python-admin-sdk-demo ❯ python sign_in_with_email_and_password.py --email your.email@yourdomain.com --password whateverpasswordyouwanttouse

### This will result in a Json response body. Just grab the value of the field named 'idToken'. ###

Once we have obtained the Firebase ID token after authenticating the user, we can go ahead and create a new Python file named send_email_verification_link.py.

import argparse
import json
import os
from pprint import pprint

import requests

FIREBASE_WEB_API_KEY = os.environ.get("FIREBASE_WEB_API_KEY")
rest_api_url = "https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode"


def get_id_token_arg():
    parser = argparse.ArgumentParser(description="Send email verification link to user")

    parser.add_argument("--firebase-id-token", required=True, help="The Firebase ID token of the user to verify.")

    return parser.parse_args()


def send_email_verification_link(id_token: str):
    payload = json.dumps({
        "requestType": "VERIFY_EMAIL",
        "idToken": id_token
    })

    r = requests.post(rest_api_url,
                      params={"key": FIREBASE_WEB_API_KEY},
                      data=payload)

    return r.json()


if __name__ == "__main__":
    arg = get_id_token_arg()
    email_address_to_verify = send_email_verification_link(arg.firebase_id_token)
    pprint(email_address_to_verify)

send_email_verification_link.py

Let’s call this a script to send an email verification link to the user’s email address.

~/demo/python-admin-sdk-demo ❯ python send_email_verification_link.py --firebase-id-token <insert-id-token-here>

{'email': 'your.email@yourdomain.com',
 'kind': 'identitytoolkit#GetOobConfirmationCodeResponse'}

Nice.

If that’s the response we see, it means that the API call was successful. Now, if we go to our email inbox, we should see an email from Firebase like this.

This is image title

Email verification link from Firebase

If you just click on the link, it will take you to a new page and if the verification is successful, you will see the following:

This is image title

Successful email verification

Some of us might have noticed that our API key is included in the email verification link above. Our first reaction would most likely be that it is not safe to do that.

However, for Firebase projects, the API key is actually public information and it is necessary to identify our Firebase project on the Google server.

Essentially, Firebase recommends the Firebase Security Rules to protect your resources. So, before deploying your app, please set the relevant security rules to protect your app resources.

Thanks for reading!

#python #firebase #data science #programming

How to Guide Verify User Email Address with Python and Firebase
47.70 GEEK