3

I am currently developing an event app in the Ionic 4 framework (with Firebase as the back-end) and I encountered a problem when creating users on the Cloud Firestore database. Whenever I use the Google or Facebook login, Firebase creates a new entry in the database although I am logging in with the same user. I've tried to implement a check, if the current user_id already exists in the database, but something seems to be wrong with my code. How can I fix it, so that my code correctly checks if the current user already exists in the database?

Currently I have the check if a user already exists in the Cloud Firestore database in my login component. I have already tried building in a check directly into the createUser() function in my user service. But the behavior was exactly the same.

this following code shows the function in my login component:

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;
        }
      }
    );

this following code shows the 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
      });
  }

this following code shows 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);
    }
  }

I am expecting the code to check if the current user already exists in my Cloud Firestore database. The actual result at the moment is, that the code ignores the check and just creates a new user on the database, even though I log in with the same user.

If anyone knows what's wrong with my code, please let me know. I would appreciate it!

2 Answers 2

2

Seems like you are comparing the uid, are you sure that the uid is the userid in your backend?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! That was actually my mistake. I changed my createUser() function to create the documents with the user.uid instead of a random generated Id and now it works! I will update my post to show my working solution.
1

I was actually comparing the uid to a randomly generated document ID in my database. I now fixed the code by giving my user object an internal_id and creating the user document on the database with the uid instead of a randomly generated document ID. And this is the working solution:

Code from my user service:

createUser(user: any): Promise<any> {
      return this.afs.collection("user").doc(user.internal_id).set({
        internal_id: user.internal_id,
        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
      });
  }

Code from my login component:

googleLogin() {
    if (this.authService.googleLogin()) {
    this.authService.getAuthState().subscribe(user => {
        if (user) {
          // User is signed in.
          console.log("Logged In ", user.email);
          this.user.internal_id = user.uid;
          this.internal_id = user.uid;
          this.user.name = user.displayName;

          this.afs.firestore.doc('user/' + this.internal_id).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;
        }
      }
    );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.