Jack Ng
Jack Ng

Reputation: 493

firestore security rule resource.data is empty object

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()

Upvotes: 5

Views: 3258

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598817

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:

Upvotes: 6

Related Questions