首页 > 解决方案 > Firebase Auth:如何在创建用户后取消订阅 Auth 观察者然后再次订阅?

问题描述

我正在使用createUserWithEmailAndPassword()注册新用户的方法。在此用户创建过程之后,我立即发送电子邮件验证。然后,onAuthStateChanged()我有一个条件来检查用户是否验证了他们的电子邮件。sendEmailVerification()问题是 Auth 观察者在电子邮件方法完成之前正在注销用户。

根据以下代码,成功取消订阅观察者的最佳地点在哪里?而且,如何使用 Firebase JS SDK v9 来做到这一点?

让我解释一下我的用例并展示我的代码:

pages/sign-up

async signUp() {
  const auth = getAuth()
  const batch = writeBatch(db)

  try {
    const UserCredential = await createUserWithEmailAndPassword(
      auth,
      this.formValues.email,
      this.formValues.password
    )
    
    const userDocRef = doc(db, 'users', UserCredential.user.uid)
    batch.set(userDocRef, {
      uid: UserCredential.user.uid,
      displayName: this.formValues.displayName,
      photoURL: `https://gravatar.com/avatar/${md5(
        this.formValues.email
      )}?d=identicon`
    })
    const usernameDocRef = doc(db, 'usernames', this.formValues.displayName)
    batch.set(usernameDocRef, { uid: UserCredential.user.uid })

    // Commit batch
    await batch.commit()
    console.log('batch committed, user is:', UserCredential.user.uid)
    await this.verifyEmail() // <-- user is logged out before this has a chance to fire!

verifyEmail()

async verifyEmail() {
  const auth = getAuth()
  const actionCodeSettings = {
    url: `${this.$config.baseUrl}/email-confirmation/success`
  }
  try {
    await sendEmailVerification(auth.currentUser, actionCodeSettings)
  } catch (error) {
    console.error('An email verification error happened', error)
    this.errorMessage = error.message
  }
},

在我的onAuthStateChanged()方法中,如果他们的电子邮件尚未验证,我会立即注销用户。这会导致以下错误:

在此处输入图像描述

这是我onAuthStateChanged设置观察者的方式(它在页面呈现之前运行):

~/plugins/auth.js

onAuthStateChanged(auth, (user) => {
  if (user) {
    if (!user.emailVerified) {
      // User has not verified the email yet
      store.dispatch('logOutUser')
    }
  // TO DO: finish up rest of user logic

取消订阅应该在页面中auth.js还是pages/sign-up页面中?我不确定如何退订。

标签: firebasefirebase-authenticationnuxt.js

解决方案


如果您需要在注册/登录后执行某些操作,那么您应该按照您的想法退订身份验证观察者。

const authObserver = onAuthStateChanged(auth, (user) => {
  // ...
}

async signUp() {
  //unsubscribe here i.e when user clicks signup button
  authObserver() 
 
  const auth = getAuth()
  const batch = writeBatch(db)
  // ...
}

请注意,如果您的身份验证观察者旨在将登录用户重定向到其他地方,那么它现在不会这样做。因此,请确保您手动执行此操作。


推荐阅读