在Firestore上定义读取操作规则的困难

时间:2018-07-14 23:06:25

标签: firebase google-cloud-firestore flutter firebase-security-rules

我在Firestore上具有以下收集结构:

> collection > {document1}  > subcollection > {document2}
document1 has the following fields:
- alias
- serial
- userID ("from request.auth.uid")

document2 has the following fields:
- date
- code

我能够创建限制写操作的规则,下面的规则集对createupdate来说很好用。

但是,当涉及到阅读动作时,它却无法如我所愿:

service cloud.firestore {
  match /databases/{database}/documents {

    function signedIn() {
      return request.auth.uid != null;
    }

    function verifiedUserSignedIn() {
        return request.auth.token.email_verified;
    }

    match /collection/{document1} {
        function ownUser_onWrites() {
        return request.resource.data.userID == request.auth.uid;
      }
        function ownUser_onReads() {
        return resource.data.userID == request.auth.uid;
      }

      allow create: if verifiedUserSignedIn();
      // Permissive update
      // TODO: must allow update only on specific fields
      allow update: if verifiedUserSignedIn() && ownUser_onWrites();
      allow read: if verifiedUserSignedIn() && ownUser_onReads();

      match /subcollection/{document2} {

        allow create: if verifiedUserSignedIn() && ownUser_onWrites();
        // Permissive update
        // TODO: must allow update only on specific fields
        allow update: if verifiedUserSignedIn() && ownUser_onWrites();
        allow read: if verifiedUserSignedIn() && ownUser_onReads();

      }
    }

// Permissive access (to be replaced)
//      match /collection/{document1=**} {
//          allow read, write: if verifiedUserSignedIn();
//      }
    match /anothercollection/{anotherdocument=**} {
        allow read, write: if verifiedUserSignedIn();
    }

  }
}

即使在使用listget操作的模拟器上也无法使用(createupdate有效)。在模拟器上,我尝试访问位置/collection/{document1},然后得到"Simulated data access denied"

在扑朔迷离的时候,我使用StreamBuilder并查询集合以匹配自己的用户userID:

...
final CollectionReference collectionReference = Firestore.instance.collection("collection");
...
      body: new StreamBuilder(
        stream: collectionReference.where('userID', isEqualTo: _userId).snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return const Text('Nothing to show');
          return new GridView.builder(
            gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 8.0 / 8.0,
            ),
            itemCount: snapshot.data.documents.length,
            padding: const EdgeInsets.all(8.0),
            itemBuilder: (context, index) =>
                widget._buildListFromCollection(context, snapshot, index, _userId),
          );
        },
      ),
...

请清楚一点,当我从ownUser_onReads()匹配项的读取规则中删除/collection/{document1}时,代码可以完美运行:

allow read: if verifiedUserSignedIn();// && ownUser_onReads(); <-- removed condition

有人吗?

0 个答案:

没有答案