typescript - 如何防止 Firebase 一遍又一遍地创建同一个用户?
问题描述
我目前正在 Ionic 4 框架中开发一个事件应用程序(以 Firebase 作为后端),在 Cloud Firestore 数据库上创建用户时遇到了问题。每当我使用 Google 或 Facebook 登录时,Firebase 都会在数据库中创建一个新条目,尽管我使用同一用户登录。如果当前 user_id 已存在于数据库中,我尝试执行检查,但我的代码似乎有问题。如何修复它,以便我的代码正确检查当前用户是否已存在于数据库中?
目前,我在我的登录组件中检查用户是否已存在于 Cloud Firestore 数据库中。我已经尝试在我的用户服务中直接在 createUser() 函数中构建一个检查。但行为完全相同。
以下代码显示了我的登录组件中的功能:
googleLogin() {
if (this.authService.googleLogin()) {
this.authService.getAuthState().subscribe(user => {
if (user) {
// User is signed in.
console.log("Logged In ", user.email);
this.userId = user.uid;
this.user.name = user.displayName;
this.afs.firestore.doc('user/' + user.uid).get()
.then(docSnapshot => {
if (docSnapshot.exists) {
console.log("user already exists");
} else {
this.userservice.createUser(this.user);
}
});
} else {
console.log("Not Logged In");
this.userId = undefined;
}
}
);
以下代码显示了我的用户服务中的功能:
createUser(user: any): Promise<any> {
return this.afs.collection("user").add({
blockPushMessages: user.blockPushMessages,
email: user.email,
isAnonymous: user.isAnonymous,
name: user.name,
partyLevel: user.partyLevel,
aliasName: user.aliasName,
dateOfBirth: user.dateOfBirth,
gender: user.gender,
homeTown: user.homeTown,
personImage_id: user.personImage_id,
registrationDate: user.registrationDate,
relationshipStatus: user.relationshipStatus,
school: user.school
});
}
以下代码显示了我的身份验证服务中的谷歌登录功能:
googleLogin() {
if (this.platform.is("cordova")) {
this.nativeGoogleLogin();
} else {
this.webGoogleLogin();
}
return true;
}
async nativeGoogleLogin(): Promise<firebase.User> {
try {
const gplusUser = await this.gplus.login({
webClientId:
"**********",
offline: true,
scopes: "profile email"
});
return await this.afAuth.auth.signInWithCredential(
firebase.auth.GoogleAuthProvider.credential(gplusUser.idToken)
);
} catch (err) {
console.log(err);
}
}
async webGoogleLogin(): Promise<void> {
try {
const provider = new firebase.auth.GoogleAuthProvider();
const credential = await this.afAuth.auth.signInWithPopup(provider);
} catch (err) {
console.log(err);
}
}
我期待代码检查当前用户是否已存在于我的 Cloud Firestore 数据库中。目前的实际结果是,代码忽略了检查,只是在数据库上创建了一个新用户,即使我使用同一个用户登录。
如果有人知道我的代码有什么问题,请告诉我。我会很感激!
解决方案
好像你在比较 uid,你确定 uid 是你后端的用户 ID 吗?
推荐阅读
- php - 在 WooCommerce 中的价格之前和之后添加文本,不包括订阅产品
- powershell - 如何查看端口后面正在运行的进程
- c# - 将 .NET 枚举转换为 GraphQL EnumerationGraphType
- asp.net - 如何使用队列系统等按钮逐个导航数据库
- entity-framework - 对象外部属性未填充
- haskell - 为什么`Concurrently`不是Haskell中的monad?
- python-3.x - KeyError:在 networkx 中使用 make_small_graph 功能时
- java - Java Servlets:Tomcat 服务器查找 MongoDB 类和包
- python - nltk.tree.Tree 对象如何生成树的字符串表示?
- mysql - Spring Hibernate @Data 更新与原始 UPDATE 查询:尽管有 @Transactional,但仍出现乐观锁异常?