Update firestore document after existing auth user's email has been verified?

Viewed 432

I am trying to give my authenticated users ( email/password users ) the ability to update their email address. After the new email address is successfully verified, I need to update the user's firestore document which is located in a users collection.

I am doing this:

async updateEmail() {
      const authUser = this.$fire.auth.currentUser
      try {
        await authUser.updateEmail(this.email) // grabbing new email address from UI form
        await this.sendEmailVerification() // sending verification email to new address with action code

        // Here I will log out the user and send them to a new page stating to 
        // check their updated email account for an email verification message
       
        this.$fire.auth.signOut()
        this.$router.replace({name: 'email-confirmation-message')
        } catch () {
            console.error(error)
        }

Question: I need to update the user's document with the following properties only after the new email address has been verified:

        await this.$fire.firestore
        .collection('users')
        .doc(authUser.uid)
        .update({
        email: this.email,
        emailVerified: true 
        })

The user should not be able to log into the app until his email is verified. The user's record should also contain the updated email address.

Should the logic for this be placed in the onAuthStateChanged listener logic, a cloud function, or ..? Any examples out in the wild that I can look at?

(I also need to keep in mind security rules as I currently have only users with verified email address, is signed in, and matches the doc uid to the auth uid. But, can adjust it accordingly...)

Thanks!

1 Answers

I'd consider making that type of change to the User document via a Cloud Function and not the client-side API. This is a somewhat sensitive operation (changing the identity of a user), so enabling/allowing update to the User document I'd be a bit paranoid about (potential security-hole wise).

I'm a bit surprised that there isn't an onUpdate trigger for Authentication. That would have been great for your use case. And I'm not sure if there is some type of trigger you can code to for when the user verifies their email address.

Related