Firestore query rules with sub collections
我有关于Firestore规则的问题。
我有一个保存文档的集合...,这些文档也有子集合....,这些文档也有子集合。
例如
1 2 3 | "Collection" ->"Document" ->"Sub-collection-1" ->"Document1" ->"Sub-collection-2" ->"Document2" (i have changed the names to make it simpler to understand) |
我在"文档"中存储了2个时间戳,用于控制用户何时可以阅读文档……它必须在" startTimestamp"之后但在" endTimestamp"之前。
我对此的规则如下。
1 2 3 | allow read: if request.auth.uid != null && int(resource.data.startReadTimestamp) < request.time.toMillis() && int(resource.data.endReadTimestamp) > request.time.toMillis() |
我的问题是,如果用户尝试读取子集合文档,例如根据父收集规则," Document1"或" Document2"以及它们根据" Document"中的时间戳记请求的时间无效吗?
如果没有,我已经看到您可以将与get结合使用的功能来访问其他文档,但这似乎很浪费,因为这将使我无法阅读。
例如这样做
1 2 3 | function getTopLevelDocData() { return get(/databases/$(database)/documents/Collection/$(documentWildcard)).data } |
我唯一想到的另一种方法是将时间戳记写入子集合中的每个文档...但这可能很难跟踪。
我们将不胜感激:)
---更新
我刚刚尝试过,它确实允许读取" Document1"如果我不调用" Document1"规则中的检查" Document"时间戳的函数,则需要澄清的是将读取" Document1"或" Document2"仅需要多读一次,因为它必须检查"文档"时间戳?
---第二次更新
想象一下上面示例中的"文档"实际上具有文档名称" 2020-08-29"。
如果我尝试读取" Document1"或" Document2",那么有一条存储规则,该规则不会引起任何文档读取,但仍会在请求时间戳(转换后)与父"文档"名称不匹配的情况下阻止读取,例如" 2020-08-29"
例如,
会起作用吗?
1 2 3 4 5 6 7 8 9 10 | match /collection/{document}{ match /Sub-collection-1/{document1}{ function transfomRequestTimestampToDate(){ return request.time.year() +"-" + request.time.month() + request.time.day(); } allow read if request.auth.uid != null && transfomRequestTimestampToDate() == {document} } } |
I just tried it and it does allow reads If i dont call the function...
您不会显示将问题中显示的
Will reading"Document1" or"Document2" be only 1 extra read as it
will have to check the"Document" timestamps?
是的,每次评估安全规则时,它将继续读取一个文档。
第二次更新后更新
是的,通过使用通配符语法,您可以使用父级的文档ID来为子级编写规则,例如,如下所示:
1 2 3 4 5 6 7 8 9 10 11 | service cloud.firestore { match /databases/{database}/documents { match /Collection/{parentDocId} { allow read: if parentDocId == '2020-08-29'; match /Subcollection1/{SubcollectionDoc} { allow read: if parentDocId == '2020-08-29'; } } } } |
,如果要使其动态化,可以执行以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 | service cloud.firestore { match /databases/{database}/documents { match /a/{a} { allow read: if a == string(request.time.year()) +"-" + string(request.time.month()) +"-" + string(request.time.day()); match /b/{b} { allow read: if a == string(request.time.year()) +"-" + string(request.time.month()) +"-" + string(request.time.day()); } } } } |
但是,请注意,