Always Learner
Always Learner

Reputation: 2952

How to restrict users from reading data from Firestore documents?

I have a database structure that looks like this:

Firestore-root
   |
   --- users (collection)
   |     |
   |     --- UidOne (document)
   |          |
   |          --- userName: "UserOne"
   |
   --- items (collection)
         |
         --- ItemIdOne (document)
         |     |
         |     --- itemName: "ItemOne"
         |
         --- ItemIdTwo
               |
               --- itemName: "ItemTwo"

What I want to achieve is to restrict every user from reading item names from each document within items collection using security rules. This is how I do it:

service cloud.firestore {
    match /databases/{database}/documents {
        match /items/{item} {
            allow read, write: if false;
        }
    }
}

To display the item names I use the following query:

Query query = itemsRef.orderBy("itemName", Query.Direction.ASCENDING);

When I try to compile my app I get the following error:

com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

But the item names are still displayed in my RecyclerView. How can I stop this from happening?

Upvotes: 0

Views: 411

Answers (1)

SammyT
SammyT

Reputation: 769

Maybe check to see if your items are still coming from the local cache.

From this page add this to your OnEvent

       String source = querySnapshot.getMetadata().isFromCache() ?
                    "local cache" : "server";
            Log.d(TAG, "Data fetched from " + source);

If it is reading from the local cache you can set PersistenceEnabled(false) like this (also mentioned on that page):

FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
        .setPersistenceEnabled(false)
        .build();
db.setFirestoreSettings(settings);

Even if you are online it will read from the local snapshot, and only updates the snapshot if the data changes. It's your rules that changed not your data. I found when testing with it set to true I got some unexpected results. I find I prefer it to be false when testing and changing code/rules.

Upvotes: 1

Related Questions