我刚刚开始了解Firestore规则,并且我的头脑正在迅速扩大。
我正在尝试解决如何将一条规则应用于一个集合,而将另一条规则应用于所有其他集合及其子集合。
因此,我从Firestore似乎附带的默认规则开始:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}这将允许对所有集合及其文档的读写访问。
但是假设我想对一个集合中的文档应用一个规则,并为所有其他集合保留默认规则。以下内容将不起作用:
service cloud.firestore {
match /databases/{database}/documents {
match /suppliers/{supplier} {
allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}
match /{document=**} {
allow read, write;
}
}
}因为第二条规则将覆盖第一条规则。
有没有办法做我想做的事?
发布于 2019-05-31 15:06:29
我知道您希望将规则应用于一个集合中的文档,并为所有其他集合保留默认规则。有一种方法可以做你想做的事情,但你不会喜欢它的。
您必须显式指定所有其他集合的默认规则。
这是一个示例。
service cloud.firestore {
match /databases/{database}/documents {
//Rule for Suppliers collection
match /suppliers/{supplier} {
allow create: if !exists(/databases/$(database)/documents/supplierABNs/1260)
}
//Rule for Changelog collection allowing complete access
match /Changelog/{id} {
allow read: if true;
allow write: if true;
}
//Rule for Vendors collection allowing complete access
match /Vendors/{id} {
allow read: if true;
allow write: if true;
}
}
}注意: Firestore规则不支持if else语句。但您可以使用AND和OR条件作为变通方法来模拟相同的情况。
发布于 2020-02-26 03:51:34
这里的基本问题是,当您有多个match语句时,如果其中任何一个match语句返回true,则允许读/写。可以在这里的文档中找到这方面的参考资料...
https://firebase.google.com/docs/firestore/security/rules-structure#overlapping_match_statements
要实现您想要执行的操作,您需要从规则中排除与所有文档匹配的特定路径。这可以通过添加检查来查看路径的第一部分是否与您排除的路径不匹配。
service cloud.firestore {
match /databases/{database}/documents {
match /suppliers/{supplier} {
allow create: if !exists(/databases/$(database)/documents/suppliers/ABNs/1260)
}
// Use this instead of the original /{document=**} check
match /{collectionName}/{document=**} {
allow read, write: if collectionName != 'suppliers';
}
}
}发布于 2018-06-06 10:38:17
service cloud.firestore {
match /databases/{database}/documents {
match /suppliers/{supplier} {
allow create: if isValidSupplier()
}
function isValidSupplier() {
return resource.data.supplierABNs == '1260'
}
match /{document=**} {
allow read, write;
}
}
}resource.data包含现有文档中的值。
https://stackoverflow.com/questions/50710650
复制相似问题