Search code examples
firebase-securityprojectiongoogle-cloud-firestore

How to filter fields in documents with security rules


I am experimenting with Cloud Firestore security rules. Is it possible to filter document fields?

For example if you have a document

{
  name: "John Doe",
  email: "[email protected]"
}

then some users aren't allowed to get the document with the email address. Their application requests the document with

firebase.firestore.doc('users/doe-uid')

and gets this document

{
  name: "John Doe",
}

If yes, how?

I think it should be possible because the Cloud Firestore Security Rules Reference says in the first sentence (emphasis is mine):

Cloud Firestore Security Rules are used to determine who has read and write access to collections and documents stored in Cloud Firestore, as well as how documents are structured and what fields and values they contain.

However I couldn't find anything in the reference telling me how to filter out fields.


Solution

  • Firestore rules are not filters, they're a server-side validation of document queries, meaning that you access (or not) the whole document, not particular fields.

    The piece of documentation you mentionned means that you can do data validation on fields. Here is a basic example of rules validating data on a write query (via request.resource.data) :

    match /users/{userId} {
        allow write: if request.resource.data.age is int;
    }
    

    Here is another basic example that uses an existing field to validate a read query (via resource.data) :

    match /articles/{articleId} {
        allow read: if resource.data.isPublished == true;
    }
    

    To filter out fields, you have do it client side, after the query.

    Now If you want to secure access to certain fields, you have to create another collection (look into subcollections) with a different set of rules, and make another query that will match these rules.