【问题标题】:Firebase Auth: How to unsubscribe from Auth observer after user creation and then subscribe again?Firebase Auth:如何在创建用户后取消订阅 Auth 观察者然后再次订阅?
【发布时间】:2021-07-28 15:08:56
【问题描述】:

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

根据以下代码,成功取消订阅观察者的最佳位置在哪里?并且,如何使用 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 页面中?我不确定如何退订。

【问题讨论】:

    标签: firebase firebase-authentication nuxt.js


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多