'Firebase security rules (.read)

I have a question about Firebase Database security rules.

I want only some documents to be reflected in the application. I tried to create a "published" field in the database, and determine if the value is true or false.

【Flutter/Dart code】

class _HomePageState extends State<HomePage> {
  late StreamSubscription<QuerySnapshot> subscription;
  late List<DocumentSnapshot> snapshot;
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection('article');

  passData(DocumentSnapshot snap) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => PostPage(snapshot: snap),
      ),
    );
  }

【In the rules of Cloud Firestore】

rules_version = '2';
service cloud.firestore {
   match /databases/{database}/documents {
    match /article/{document=**} {
       allow read:if resource.data.published == 'true';
    }
  }
}

【In the Cloud firestore】

collection → article
field → published : false

In the above case, is it recognized that the information in document is not reflected in the application?

I checked with the Xcode simulator, but it is also reflected.



Solution 1:[1]

I assume that your code tries to read all documents from collectionReference. If that is the case, then your rules will reject that read, because they say that any user is only allowed to read published documents.

The key to understand here is that rules are not filters themselves, but instead merely ensure that any operation only tries to read documents that it is allowed to read.

So for your read operation to work, you should query to only request documents that have been published.

That'd be something like:

collectionReference.where("publish", isEqualTo: "true");

Note that I pass 'true' as a string here, since that's what your rules also check for. It is more custom to store true/false as actual boolean values, so I'd recommend doing that if possible.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen