Firebase安全规则如何删除除指定路径之外的所有路径

wljmcqd8  于 11个月前  发布在  其他
关注(0)|答案(4)|浏览(103)

让我们假设一组规则具有以下字段:

service cloud.firestore {
   match /databases/{database}/documents {
     match /stories/{story} {}
     match /comments/{comment} {}
     match /posts/{post} {}
  }
}

字符串
我们想为所有剩余的集合添加一个新的匹配条件,使用的是一个“来”排序。
我该如何实现这一点?

bogh5gae

bogh5gae1#

我相信这是不可能的。如果你在一场比赛中使用一个类似这样的集合:

match /{collection}/{doc} { ... }

字符串
然后,它将匹配所有集合中的所有文档,包括故事,评论和帖子。这肯定不是你想要的。没有办法用子字符串或正则表达式匹配。它总是适用于整个集合或路径中的文档ID。

owfi6suc

owfi6suc2#

您可以通过使用Firestore Rulesversion 2中最近引入的递归通配符来完成此操作。但您需要像这样指定规则版本:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    // Matches any document in collection and subcollections
    match /{path=**} {
      allow read, write: if <condition>;
    }
  }
}

字符串
更多详情请访问:https://firebase.google.com/docs/firestore/security/rules-structure#recursive_wildcards

erhoui1w

erhoui1w3#

我最近遇到了这个问题,我想出了一个解决方案。通配符(非递归)不仅可以在文档级别,也可以在集合名称级别。
您的示例的解决方案可能是:

service cloud.firestore {
   match /databases/{database}/documents {
     match /{collection}/{docName}/{document=**} {
         allow read: if collection == 'comments';
         allow write: if collection != 'posts';
    }
  }
}

字符串
举个例子,我希望我已经说清楚了

kcwpcxri

kcwpcxri4#

我的项目需要这样做,我已经通过利用request.path并为我需要从通配符中排除的路径添加例外来解决这个问题:

service cloud.firestore {
    match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if <condition> && !isExcludedPath();
        }
        match /stories/{story} {}
        match /comments/{comment} {}
        match /posts/{post} {}


        function excludedCollections(){
            return ["stories", "comments", "posts"]
        }

        function pathContainsAny(pathArray){
            return string(request.path).split("/").hasAny(pathArray)
        }
        function isExcludedPath(){
            return pathContainsAny(excludedCollections())
        }
    }
}

字符串
string(request.path)-这种强制对于这种方法来说是至关重要的,是最近才引入的,所以如果您在这里遇到错误,请将firebase-tools升级到最新版本。

相关问题