Firestore规则:如何允许基于父属性读取嵌套文档

时间:2018-12-28 13:14:14

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

我有一个firstore数据库,其中包含如下所示的集合和文档:

  • 用户->事件->活动->流

我希望每个人都能够读取“事件”集合中的文档,如果“事件”文档具有属性,例如对字符串“ public”的可见性,则该文档是子集合文档(活动+流)

因此,如果“事件”集合上的文档对公众具有可见性,则任何用户都应该能够阅读该文档及其子集合。

到目前为止,我设法通过以下方式使事件集中的文档可读:

   service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userID} {
      allow read, update, delete: if request.auth.uid == userID;
      allow create: if request.auth.uid != null;
        match /events/{eventID} {
          allow read: if resource.data.visibility == 'public';
          allow read, write, create, update, delete: if request.auth.uid == userID;
          match /activities/{activitytID} {
            allow read, write, create, update, delete: if request.auth.uid == userID;
            match /streams/{streamID} {
              allow read, write, create, update, delete: if request.auth.uid == userID;
            }
          }
        }

    }
  }
}

当一个事件文档的可见性公开时,如何使嵌套的活动和流集合也可读?

1 个答案:

答案 0 :(得分:0)

我通过以下方法解决了这个问题:

添加了获取事件数据的功能

 function eventData() {
            return get(/databases/$(database)/documents/users/$(userID)/events/$(eventID)).data
          }

完整规则:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userID} {
      allow read, update, delete: if request.auth.uid == userID;
      allow create: if request.auth.uid != null;
        match /events/{eventID} {
          allow read: if resource.data.visibility == 'public';
          allow read, write, create, update, delete: if request.auth.uid == userID;
          function eventData() {
            return get(/databases/$(database)/documents/users/$(userID)/events/$(eventID)).data
          }
          match /activities/{activityID} {
            allow read: if eventData().visibility == 'public'
            allow read, write, create, update, delete: if request.auth.uid == userID;
            match /streams/{streamID} {
              allow read: if eventData().visibility == 'public'
              allow read, write, create, update, delete: if request.auth.uid == userID;
            }
          }
        }

    }
  }
}