5

In firestore security rule, the resource.data is an emtpy object always, is this a bug or something ?

My firestore rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /hospitals/{document=**}{

      // allow read :if resource.data.size() == 0; //this return true, resource.data is an empty object

          allow read :if resource.data.name != null; // this doesn't work
    }
  }
}

My javascript:

auth().onAuthStateChanged((user) => { 
  if (user) {

    //db is the firestore instance
    db.collection('/hospitals').get()
      .then(printResult)

  } else {
    
  }
}) 

this is my current database snapshot image

solved :

thanks for Frank's answer

the issue rely on that firestore security doesn't evaluate the actual document value when we query a over multiple document , in my case

//this doesn't firestore doesnt' evaluate the documetn
db.collection('hospitals').get()

//this will work ,if you need to compare the actual value
db.document('hospitals/somehospital').get()
Jack Ng
  • 473
  • 7
  • 14
  • i corrected my question, my apology – Jack Ng May 01 '18 at 01:09
  • Even with the update, it's hard to say what's going on without seeing the code that is giving you unexpected results. See [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) for how to make it easiest to help you. – Frank van Puffelen May 01 '18 at 04:36
  • i added my javasript code above – Jack Ng May 01 '18 at 09:04
  • when i use the rule " // allow read :if resource.data.size() == 0; " , i am able to retrieve all the document, but i failed when i try to access the "resource.data.name != null" – Jack Ng May 01 '18 at 09:06

1 Answers1

6

Security rules don't filter data by themselves. They merely enforce rules on what data a client can read. Your client is currently trying to read all hospitals. Since your security rules have restrictions on what data a client can read, they reject this operation.

You need to ensure that what your client requests is no more than what the security rules allow, by reading the data through a query that matches the security rules. So something like

db.collection('/hospitals')
  .where("name", ">=", "")
  .get()
  .then(printResult)

Note that this does require that the document has a name field, otherwise the name can't be empty.

For more info, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 3
    From the documentation [Firestore documentation on securing queries](https://firebase.google.com/docs/firestore/security/rules-query) **To save you time and resources, Cloud Firestore evaluates a query against its potential result set instead of the actual field values for all of your documents.** does it mean when we query multiple documents at a time, firestore security rule would not evaluate the the actual value for each document? – Jack Ng May 02 '18 at 02:41