javascriptfirebasegoogle-cloud-firestorefirebase-authenticationangularfire

How not to overwrite user data in FireStore for returning user when login using Angularifre?


I am using AngularFire auth and it will create a User document when a user signs in.

async googleSignin() {
const provider = new firebase.auth.GoogleAuthProvider();
const credential = await this.afAuth.signInWithPopup(provider);
return this.createUserData(credential.user);
}
private createUserData(user: any) {
// Sets user data to firestore on login
this.userDoc = this.afs.doc(`users/${user.uid}`);

const data = {
  uid: user.uid,
  email: user.email,
  displayName: user.displayName,
  photoURL: user.photoURL,
  instructor: false,
};

return this.userDoc.set(data, { merge: true });
}

The issue with this is when a returning user signs back in, it will overwrite the user document.

For example, when the user changes their profile picture on their document. When they logged out and log back in it will set according to the data set when signing.

I am not sure if this is an obvious logic, but I'm new to this. Appreciate the help.

Thank you in advance.


Solution

  • It seems that all you need is to check if the user already exists.

    Something like this should do the trick :

    private async createUserData(user: any) {
      this.userDoc = this.afs.doc(`users/${user.uid}`);
      const documentSnapshot = await userDoc.get()
    
      if (documentSnapshot.exists) {
        return;
      }
    [...]
    

    See the DocumentReference and DocumentSnapshot documentation

    I am a little concerned about security in your code though. Creating the user document from the frontend like that may be a problem if you don't have the right firestore rules in place. Make sure to have a rule such as

    match /user/{userId} {
      allow read, write: if request.auth.uid == userId
    }
    

    Otherwise any user could overwrite any other user's profile information