Skip to content Skip to sidebar Skip to footer

How To Only Store Data For Current Logged In User Using Firestore

Below is the code which allows the user to store data into Firestore. The problem is, the uploaded data is viewable for all the users logged into the app. How would I be able to o

Solution 1:

How to only store data for current logged in user using Firestore

You can achieve the same thing if you pass the uid to the document() method. So the following lines of code used in Firebase real-time database:

FirebaseUseruser= FirebaseAuth.getInstance().getCurrentUser();
StringuserId= user.getUid();
mDatabaseRef = FirebaseDatabase.getInstance().getReference(FB_DATABASE_PATH).child(userId);

Is equivalent in Firestore with:

Stringuid= FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestorerootRef= FirebaseFirestore.getInstance();
DocumentReferenceuidRef= rootRef.collection("users").document(uid);
POJOpojo=newPOJO();
uidRef.set(pojo);

Solution 2:

You would need to add a firestore rule to prevent a user from adding data to another user. Just check the auth userid in firestore and compare it to the userid on the document.

Post a Comment for "How To Only Store Data For Current Logged In User Using Firestore"