【发布时间】: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