Javascript 使用firestore创建安全的REST类API

Javascript 使用firestore创建安全的REST类API,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我想在firebase中存储一对多关系。假设我有一位作者,有些书是属于这位作者的。我可以将其存储在嵌套关系中: author/ authorId1 : { books: [{...}, {...}] } 但我还需要一种列出所有书籍的方法,最好不要遍历每个作者(需要实时数据库的afaik),所以我想我应该这样做 author/ authorId1 : { books: [bookId1, bookId2] } books/ bookId1: {...} b

我想在firebase中存储一对多关系。假设我有一位作者,有些书是属于这位作者的。我可以将其存储在嵌套关系中:

author/
  authorId1 : {
    books: [{...}, {...}]
  }
但我还需要一种列出所有书籍的方法,最好不要遍历每个作者(需要实时数据库的afaik),所以我想我应该这样做

author/
  authorId1 : {
    books: [bookId1, bookId2]
  }
books/
  bookId1: {...}
  bookId2: {...}
但出于安全和性能方面的考虑,我不希望在前端进行过滤。我发现可以编写查询:

const bookRef = fireStore.collection('books');
debtorsRef.where('author', '==', authorId).then(...);
这有望消除性能问题,但不安全,因为可以从客户端获取其他作者的书籍。另外,我更愿意将关系存储在作者文档中,而不是相反

在使用Django Rest框架的restful API上,我将限制查询集只返回属于给定用户的书籍。IIUC这是可能的,但根据例子,我不太确定如何

同样,我只想在其id列在作者的books属性中时才返回该书。理论上,一本书可能属于多个作者

我想这是一个重复,许多人都有这种担心,但我找不到这个特定用例的明确答案。

您可以编写以下代码来确保查询的安全:

service cloud.firestore {
  match /databases/{database}/documents {
    match /books/{bookId} {
      allow read: if request.resource.data.author == resource.data.author
    }
  }
}

请注意,目前我们只支持等式约束(
==
),而不支持不等式(
!=
),因此,如果我理解正确,目前无法检查作者是否具有bookId。在每本书可能属于多个用户的情况下,如何表示多对一关系?
service cloud.firestore {
  match /databases/{database}/documents {
    match /books/{bookId} {
      allow read: if exists(/databases/$(database)/documents/books/$(bookId)/owners/$(request.auth.uid))
      match /owners/{ownerId} {
        // Include other conditions that provide for ownership checks
        allow write: if request.auth.uid == ownerId;
      }
    }
  }
}