firebase - 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
页面中?我不确定如何退订。
解决方案
如果您需要在注册/登录后执行某些操作,那么您应该按照您的想法退订身份验证观察者。
const authObserver = onAuthStateChanged(auth, (user) => {
// ...
}
async signUp() {
//unsubscribe here i.e when user clicks signup button
authObserver()
const auth = getAuth()
const batch = writeBatch(db)
// ...
}
请注意,如果您的身份验证观察者旨在将登录用户重定向到其他地方,那么它现在不会这样做。因此,请确保您手动执行此操作。
推荐阅读
- tmux - tmux 没有读取 /usr/local/etc 中的配置文件 tmux.conf
- kubernetes-vitess - 如何在多区域 Kubernetes 环境中连接 vitess
- django - 关键错误 django - 使用 django 表单传递其他内容
- javascript - var 关键字的 if 语句与功能块
- javascript - 使用 setState 反应 Hook useEffect 问题
- mediawiki - 避免在清漆中缓存来自 Special:Random 的重定向
- java - 在 Jboss7.1.1EAP 和 Oracle 11g 中为单个 sqlID 事务创建多个 Oracle 长时间运行会话
- apache-kafka - Kafka Connect:多个独立连接器可以写入同一个 HDFS 目录吗?
- apache-kafka - 无法使用 CONDUKTOR UI 连接到 Kafka
- azure - 从 Azure 应用程序访问所有用户驱动器