Firestore Safety Rules

Regarding the Firebase Realtime database security rules, both public and private data can exist in the same tree using the following rule.

However, when using Firestore, it does not seem to allow us to do the same, because the data cartridge that we can get is only under the collection or document. When public and private data are defined in one document and receive w / collection / document data, we will receive an error with insufficient permissions, as for private data if we are not the owner.

When using RTDB, we can get the data "users / {userId} / publicInfo" because we have no idea about the collection / document.

Is there a way to do this with RTDB with Firestore? Otherwise, should we have a public / private collection separately?

// rule of Firebase Realtime Database
"users": {
   "$user_id": {
       ".read": "auth.uid === $user_id",
       ".write": "auth.uid === $user_id",

       "private": {
          ".read": "auth.uid === $user_id"   // --- private data
       }

       "public": {
          ".read": "auth !== null";           // --- public data 
       }
   }
}

// Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {

      match /{private=**} {
        allow read, write: if request.auth == userId;
      }

      match /{public=**} {
        allow read, write: if request.auth != null;
      }
    }
  }
}
+4
source share
1 answer

Therefore, you cannot have separate security rules for individual parts of a document. You can either read the entire document or you cannot.

However, if you want to provide your document userID with “public” and “private” subcollections containing public and private documents, this is something you can do completely, just not the way you currently set up your security rules.

match /{private=**}, , : " , 'private'". : " , , , private". .

, request.auth.uid, .

, , , - :

// Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      // You'll probably want to add security rules around the user document 
      // itself. For now, though, let look at our subcollections:

      match /private/{anything=**} {
        // Only the user can read documents in their private collection
        allow read, write: if request.auth.uid == userId;
      }

      match /public/{anything=**} {
        // Anybody can read documents here, as long as they're signed in
        allow read, write: if request.auth != null;
      }
    }
  }
}
+8

Source: https://habr.com/ru/post/1686959/


All Articles