While developing an event app using the Ionic 4 framework with Firebase as the back-end, I ran into an issue with user creation on the Cloud Firestore database. Every time a user logs in using Google or Facebook, Firebase creates a new entry in the database even if the user is the same. I have tried to implement a check to see if the user_id already exists in the database, but there seems to be an issue in my code. How can I troubleshoot and correct this problem so that my code accurately verifies if the current user already exists in the database?
The existing code has the check for user existence in the Cloud Firestore database within the login component. I also attempted to integrate the check directly into the createUser() function in my user service, but the behavior remained unchanged.
Here is the function in my login component:
googleLogin() {
if (this.authService.googleLogin()) {
this.authService.getAuthState().subscribe(user => {
if (user) {
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;
}
}
);
Here is the createUser function in my user service:
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
});
}
And here are the google login functions in my auth service:
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);
}
}
My expectation is that the code should verify if the current user already exists in the Cloud Firestore database. However, the current behavior is that the check is ignored, and a new user is created in the database even if the user is the same. If anyone can identify the issue with my code, I would greatly appreciate your insight!