Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only particular fields of a firestore document to be accessed publicly

Suppose I have this structure in a firestore database:

collection[
  document: {
    x: 'x',
    y: 'y'
  }
]

and I have this firebase rule in place:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
    }
  }
}

But this rule exposes the whole document in the above collection, What I want to do is to expose only x field, is it possible? Thanks

like image 603
Muhammad Saqib Avatar asked Oct 30 '17 09:10

Muhammad Saqib


2 Answers

You can't. Security rules only work on a document-level basis, so you can't restrict read access to specific fields.

If you want to do something like you're suggesting, you'll probably need to restructure your data so that your non-public data is in a separate document. Most likely you'll want to do this by putting your private data in a subcollection. So you might end up with something like this...

collection: [
  document: {
    y: 'y'
    private-collection: [
      document: {
        x: 'x'
      }
    ]
  }
]

And then you'd set up your security rules like:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
      match /private-collection/{otherdoc} {
        allow read: if someOtherRuleThatYouAddHere();
      }
    }
  }
}
like image 170
Todd Kerpelman Avatar answered Oct 03 '22 06:10

Todd Kerpelman


YOU CAN!

not do this for reading, but for updating. This is not what was asked for, but it's probably what many people came here for - including myself.

allow update: request.resource.data.diff(resource.data).affectedKeys().hasOnly(['MyField']);

Docs

like image 25
Lukas Niessen Avatar answered Oct 03 '22 04:10

Lukas Niessen