我有两种方法可以在 Firebase 中注册用户:通过电子邮件和通过 Google 登录。
我通过电子邮件执行用户注册如下:
signUp() {
const auth = getAuth();
const db = getFirestore();
createUserWithEmailAndPassword(
auth,
this.createEmail,
this.createPassword
).then(
(userCredential) => {
const user = userCredential.user;
this.$router.push("/");
addDoc(collection(db, "users"), {
email: this.createEmail,
name: this.createName,
});
},
);
},
换句话说,除了在 Firebase 身份验证中保存用户之外,我还将他们的姓名和电子邮件发送到 Firestore。这是我的第一个问题:
最后,通过谷歌登录完成如下:
googleSignIn() {
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
this.$router.push("/");
addDoc(collection(db, "users"), {
email: result.user.email,
name: result.user.displayName,
});
})
},
这里出现了一个问题,因为如果用户在 Firebase 身份验证中多次登录,一切正常,但在 Firebase Firestore 中,每次使用 Google 新登录都会创建一个用户。
首先,我将移动router.push()
下面的语句,addDoc()
以便我可以确认文档已添加,然后用户被重定向到其他页面。在使用 Google SignIn 的情况下,您可以isNewUser
通过获取附加信息访问该属性来检查用户是否是新用户。如果为 true,则将文档添加到 Firestore,否则重定向到仪表板:
signInWithPopup(auth, provider)
.then(async (result) => {
// Check if user is new
const {isNewUser} = getAdditionalUserInfo(result)
if (isNewUser) {
await addDoc(collection(db, "users"), {
email: result.user.email,
name: result.user.displayName,
});
}
this.$router.push("/");
})
将文档 ID 设置为用户的 Firebase 身份验证 UID 而不是使用addDoc()
哪个生成另一个随机 ID可能是个好主意,这样更容易编写安全规则。尝试将代码重构为:
signInWithPopup(auth, provider)
.then(async (result) => {
// Check if user is new
const {isNewUser} = getAdditionalUserInfo(result)
const userId = result.user.uid
if (isNewUser) {
await setDoc(doc(db, "users", userId), {
email: result.user.email,
name: result.user.displayName,
});
}
this.$router.push("/");
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句