Firestore security rules : searching for a user's id in array in a document

前端 未结 2 2012
故里飘歌
故里飘歌 2020-12-05 07:03

First, sorry for my terrible English, it is not my native language...

I am building a simple app in Firebase, using the Firestore database. In my app, users are memb

相关标签:
2条回答
  • 2020-12-05 07:13

    In general, you need to write a rule like the following:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /collection/{documentId} {
          // works if `members` = [uid1, uid2, uid3]
          // no way to iterate over a collection and check members
          allow read: if request.auth.uid in resource.data.members;
          // you could also have `members` = {uid1: {}, uid2: {}}
          allow read: if resource.data.members[request.auth.uid] != null;
        }
      }
    }
    

    You could also use subcollections:

    service cloud.firestore {
      match /databases/{database}/documents {
        // Allow a user to read a message if the user is in the room
        match /rooms/{roomId} {
          match /documents/{documentId} {
            allow read: if exists(/databases/$(database)/documents/documents/$(documentId)/users/$(request.auth.uid));
          }
          match /users/{userId} {
            // rules to allow users to operate on a document
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-05 07:26

    I made it happen with this code

    Allow some user to read/write some document of a collection if this same user is present into an array of another collection

    service cloud.firestore {
      match /databases/{database}/documents {
        match /repositories/{accountId} {
          allow read, write: if request.auth.uid in get(/databases/$(database)/documents/accounts/$(accountId)).data.users
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题