Skip to content

Instantly share code, notes, and snippets.

@mcapodici
Created June 1, 2023 03:03
Show Gist options
  • Save mcapodici/edd0b843eb7af1038d3bc42367b0ef7d to your computer and use it in GitHub Desktop.
Save mcapodici/edd0b843eb7af1038d3bc42367b0ef7d to your computer and use it in GitHub Desktop.

Certainly! I can help you understand how to use the get() function in Firestore security rules to make permissions dependent on data within another collection. Although I don't have the ability to share photos directly, I can guide you through the process step by step.

Let's assume you have a Firestore database structure as follows:

- parentCollection (collection)
  - documentA (document)
    - subCollectionX (collection)
      - subDocumentX (document)
  - documentB (document)
    - subCollectionY (collection)
      - subDocumentY (document)

To set up security rules based on data from subCollectionX and subCollectionY, you can follow these steps:

  1. Access subCollectionX from documentA:
function checkSubCollectionX(documentId) {
  return get(/databases/$(database)/documents/parentCollection/documentA/subCollectionX/$(documentId)).data;
}

Here, documentId is the ID of the document you want to access within subCollectionX. The get() function is used to retrieve the document data, and .data is used to access the fields within the document.

  1. Access subCollectionY from documentB:
function checkSubCollectionY(documentId) {
  return get(/databases/$(database)/documents/parentCollection/documentB/subCollectionY/$(documentId)).data;
}

Similarly, documentId is the ID of the document you want to access within subCollectionY. The get() function retrieves the document data, and .data is used to access the fields within the document.

You can then use these functions in your security rules to check permissions based on the data from subCollectionX and subCollectionY. For example, let's say you want to allow read access to a collection someCollection only if a certain field in subCollectionX matches a value in subCollectionY:

match /someCollection/{documentId} {
  allow read: if checkSubCollectionX(documentId).fieldName == checkSubCollectionY(documentId).fieldName;
}

In this rule, fieldName represents the specific field you want to compare.

These examples demonstrate how to use the get() function to retrieve data from two sub-collections within a parent collection and how to incorporate that data into your security rules. Remember to adjust the paths and field names to match your database structure.

I hope this explanation helps you understand how to use the get() function in Firestore security rules. If you have any further questions, feel free to ask!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment