用于在用户之间共享文档的Firestore数据库规则和结构

时间:2017-10-08 13:04:16

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

我正在尝试创建一个允许用户在列表上进行协作的应用程序。需要邀请每个用户才能在列表中工作。

我像这样构建了我的数据(基于this blog post)。 如果需要,也可以更改此结构。

list
  list_1:
    users:
      owner:
        owner@company.com: true
      shared:
        user@company.com: true
        user2@company.com: true
    id
    name
    items:
      item_1:
        id:
        name:
      ...

我想要实现的目标:每个人都应该能够创建列表。然后,他们的创建者将成为创建列表的所有者。 只有"共享"中的所有者和用户文档应该能够读取和写入此列表。

我想权限设置看起来应该是这样的。但这不起作用:

service cloud.firestore {
  match /databases/{database}/documents {
    match /lists/{listId}/{anything=**} {
        allow read, write: if !exists(resource.data.users.owner) ||
                               resource.data.users.owner == request.auth.token.email ||
                               request.auth.token.email in resource.data.users.shared
    }
  }
}

1 个答案:

答案 0 :(得分:4)

我能够弄明白。

我将数据结构更改为:

list
  list_1
    owner: owner@company.com
    writeAccess: [user1@company.com, user2@company.com]
    id
    name
    items:
      item_1:
        id:
        name:
      ...

然后像这样的数据库规则正在运行:

service cloud.firestore {
  match /databases/{database}/documents {
    match /lists/{listId} {
        // Allow RW on lists for owner, shared user or for everyone if it's a new list
      allow read, write: if resource.data.owner == request.auth.token.email ||
                            request.auth.token.email in resource.data.writeAccess ||
                            !exists(/databases/$(database)/documents/lists/$(listId))
    }
    match /lists/{listId}/items/{itemId} {
        // Allow RW on item for owner or shared user of parent list
        allow read, write: if get(/databases/$(database)/documents/lists/$(listId)).data.owner == request.auth.token.email ||
                              request.auth.token.email in get(/databases/$(database)/documents/lists/$(listId)).data.writeAccess ||
                             !exists(/databases/$(database)/documents/lists/$(listId)) // Needed for new lists. Because lists and items are created in a batch
    }
  }
}