【问题标题】:Firestore security rules for `list` request`list` 请求的 Firestore 安全规则
【发布时间】:2018-10-01 16:36:35
【问题描述】:

在 Firestore 安全规则中,是否可以在使用 list 查询时检查某些文档字段?

使用 Angular,我想使用其 username 属性从 userprofiles 集合中检索单个文档,如下所示:

let userprofile = this.afs.collection( 'userprofiles', ref => 
ref.where('username', '==', username ).limit(1);

如果满足以下任一条件,我希望 Firestore 安全规则允许此查询:

  • 用户配置文件已发布,或
  • 用户配置文件未发布,但相应用户已登录

这是我的 Firestore 安全规则:

match /userprofiles/{userprofileId} {

    allow list:  if( resource.data.published==true || (    
                     resource.data.published==false &&
                     resource.data.uid==request.auth.uid )
                 );
    }
}

对于上下文,我使用完全相同的规则来允许 get 请求,这很好。但是,上面示例中的查询会导致list 请求,而不是get。在这种情况下,这些规则不允许查询。我收到Error: Missing or insufficient permissions.

我记得读过类似列表查询的内容,规则必须允许所有文档或不允许文档,在我的情况下不适用。所以我有点理解为什么它不起作用。

我的问题是,我可以更改一些内容以使其适用于我的查询吗?或者这是不可能的?任何解决方法的想法? (除了明显的“按文档ID查询”或“使用户名成为文档ID”)

【问题讨论】:

  • 您解决了这个问题吗?我遇到了一种情况,我可以直接通过 id 获取文档,但是当我执行 where 查询来检查 id == MYID (这是一个有一个结果的列表)时,它会因为权限被拒绝而失败。

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


【解决方案1】:

我迟到了,但这样的陈述在我的情况下有效

match /userprofiles/{userprofileId} {
    allow read: if resource.data.published==true;
    }
}
match /userprofiles/{userprofileId} {
    allow read: if resource.data.uid==request.auth.uid;
    }
}

【讨论】:

    【解决方案2】:

    为了允许“列表”进行查询,查询参数必须符合安全规则。请参考the documentation.

    您的查询需要包含已发布的==true 语句:

    let userprofile = this.afs.collection( 'userprofiles', ref => 
    ref.where('published', '==', true).where('username', '==', username ).limit(1);
    

    您的规则可以简化为:

    match /userprofiles/{userprofileId} {
    
        allow list: if resource.data.published==true || 
                       resource.data.uid==request.auth.uid;
    }
    

    请注意,查询只会列出已发布的用户配置文件。我认为不可能一次查询“published==true”或匹配 uid 条件,您的代码需要查询两次。

    【讨论】:

    • 完全错过了文档的那部分。您的回答结束了漫长而令人沮丧的故障排除会话,谢谢! [我不是 OP]
    • 如果查询中不允许,我们将如何匹配安全规则中的 or 语句?例如如何匹配这个规则:allow list: if request.auth.uid in resource.data.receiversUids || request.auth.uid == resource.data.senderUid;
    猜你喜欢
    • 2021-07-29
    • 2018-08-04
    • 2019-03-05
    • 2018-10-19
    • 2019-07-05
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多