Firebase Cloud functions and email verification Flutter app development company Web app development company Best mobile app development company Part 3 Firebase Cloud Functions for Email Verification

Part 3: Firebase Cloud Functions for Email Verification

In the previous parts of our blog series, we established the user interface and set up the SMTP mailer to send verification emails in our Flutter application. Now, in Part 3, we will focus on setting up Firebase Cloud Functions for the email verification process when users click the link in their emails. This is a critical step to ensure that users can successfully verify their accounts and gain access to the application.

Firebase Cloud Functions

Firebase Cloud Functions allows you to run backend code responding to events triggered by Firebase features and HTTPS requests. In this context, we will implement a Cloud Function for email verification that listens for requests initiated by the email verification link sent to users. This function will validate the link, check its expiration time, and update the user’s status in Firestore.

Advantages of Using Firebase Cloud Functions for Email Verification

  1. Scalability: Cloud Functions automatically scale based on incoming requests. You don’t need to worry about managing server infrastructure, as Firebase handles scaling for you. Whether you have a few users or thousands, Cloud Functions can manage the load.
  2. Cost-Effectiveness: With a pay-as-you-go pricing model, you only pay for the compute time you use. This makes it economical, especially for startups or projects with variable traffic, as you won’t incur costs when your function is idle.
  3. Simplified Deployment: Firebase provides a streamlined process for deploying Cloud Functions. You can easily update and manage your functions without the need for complex deployment procedures, making it simpler to iterate on your email verification logic.
  4. Enhanced Security: By using Cloud Functions, you can keep sensitive logic off the client side. For instance, the email verification process relies on secure server-side operations to validate links and update user statuses, reducing the risk of unauthorized access.
  5. Integration with Other Firebase Services: Cloud Functions work seamlessly with other Firebase services, such as Firestore and Authentication. This allows for easy data manipulation and retrieval, enabling a cohesive application architecture.

Implementing the Cloud Function

Below is the implementation of the emaillinkLogin Cloud Function:

exports.emaillinkLogin = functions.https.onRequest(async (req, res) => {
    const userId = req.query.userId;
    const timeParam = req.query.Time;

    // Check for missing parameters
    if (!userId || !timeParam) {
        return res.status(400).send("Missing userId or Time in the request");
    }

    try {
        // Get the current time in seconds
        const currentTime = Math.floor(Date.now() / 1000);
        const fiveMinutesAgo = currentTime - (5 * 60); // Calculate the time 5 minutes ago

        // Convert timeParam to an integer
        const timeParamInt = parseInt(timeParam, 10);

        // Check if the provided time is within the last 5 minutes
        if (timeParamInt >= fiveMinutesAgo && timeParamInt <= currentTime) {
            const userRef = admin.firestore().collection("users").doc(userId);
            
            // Update the user's email verification status
            await userRef.update({
                emailRequestStatus: "verificationSuccess"
            });

            res.status(200).send("Email verified successfully");
        } else {
            // If the time is not valid, respond with link expired
            res.status(403).send("Link expired");
        }
    } catch (error) {
        console.error("Error verifying email:", error);
        res.status(500).send("Error verifying email");
    }
});

Explanation of the Code

  1. Exporting the Function:
    • The function is exported as emaillinkLogin, which will handle HTTPS requests.
  2. Extracting Query Parameters:
    • The function retrieves the userId and Time parameters from the request query. If either parameter is missing, it responds with a 400 status code indicating a bad request.
  3. Current Time Calculation:
    • The current time in seconds is calculated. Additionally, it computes the timestamp for five minutes ago to validate the expiration of the link.
  4. Time Validation:
    • The function checks if the provided timeParam falls within the last five minutes. If it does, it proceeds to update the user’s email verification status in Firestore.
  5. Updating Firestore Document:
    • The function accesses the Firestore database, retrieves the user document by userId, and updates the emailRequestStatus field to indicate that the email has been verified successfully.
  6. Response Handling:
    • If the verification is successful, it responds with a 200 status code and a success message. If the link is expired, it returns a 403 status code with an appropriate message. In case of any errors during execution, it catches the error, logs it, and responds with a 500 status code.

Best Practices for Firebase Cloud Functions For Email Verification

  1. Error Handling: Always implement error handling to capture and respond to unexpected issues gracefully.
  2. Security: Ensure that sensitive data, such as user IDs, is handled securely and not exposed inappropriately through logs or responses.
  3. Scalability: Design your functions to be efficient and scalable, considering the number of potential users and verification requests.

Conclusion

In this part of our blog series, we set up the Firebase Cloud Function for email verification requests securely and effectively. This function plays a crucial role in the user authentication process, ensuring that only users who have verified their email addresses can access your application.

In the next part, we will discuss how to set up a snapshot listener in your Flutter app to listen for changes in user verification status and navigate users accordingly. Stay tuned for Part 4, where we will enhance the user experience further!

Recent Blogs


Posted

in

,

by

Tags:

To Know Us Better

Browse through our work.

Explore The Technology Used

Learn about the cutting-edge technology and techniques we use to create innovative software solutions.