Firestore 安全规则:在文档的数组中搜索用户的 id [英] Firestore security rules : searching for a user's id in array in a document

查看:25
本文介绍了Firestore 安全规则:在文档的数组中搜索用户的 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不起我糟糕的英语,它不是我的母语......

First, sorry for my terrible English, it is not my native language...

我正在 Firebase 中使用 Firestore 数据库构建一个简单的应用程序.在我的应用程序中,用户是小组的成员.他们可以访问其他用户的数据.为了不查询太多文档(每个用户一个,在组文档的子集合中),我选择将用户数据添加到组文档内的数组中.这是我组的文档:

I am building a simple app in Firebase, using the Firestore database. In my app, users are members of small groups. They have access to other users' data. In order not to query too many documents (one per user, in a subcollection of the group's document), I have chosen to add the users' data in an array inside the group's document. Here is my group's document:

{
   "name":"fefefefe",
   "days":[false,false,false,false,true],
   "members":[
       {"email":"eee@ff.com","id":"aaaaaaaa","name":"Mavireck"}, 
       {"email":"eee2@ff.com","id":"bbbbbbbb","name":"Mavireck2"}, 
   ],
}

如果用户在组中,我如何检查安全规则?我应该改用一个对象吗?我真的不想为用户使用子集合,因为我会很快达到免费配额的限制......

How can I check with the security rules if a user is in a group ? Should I use an object instead ? I'd really prefer not use a subcollection for users, because I would reach the free quota's limits too quickly...

感谢您的时间!

谢谢你的回答.我将其更改为一个对象:"成员": { uid1 : {}, uid2 : {} }

Thanks for the answer. I will change it to an object : "Members": { uid1 : {}, uid2 : {} }

推荐答案

一般来说,你需要编写如下规则:

In general, you need to write a rule like the following:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{documentId} {
      // works if `members` = [uid1, uid2, uid3]
      // no way to iterate over a collection and check members
      allow read: if request.auth.uid in resource.data.members;
      // you could also have `members` = {uid1: {}, uid2: {}}
      allow read: if resource.data.members[request.auth.uid] != null;
    }
  }
}

您也可以使用子集合:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow a user to read a message if the user is in the room
    match /rooms/{roomId} {
      match /documents/{documentId} {
        allow read: if exists(/databases/$(database)/documents/documents/$(documentId)/users/$(request.auth.uid));
      }
      match /users/{userId} {
        // rules to allow users to operate on a document
      }
    }
  }
}

这篇关于Firestore 安全规则:在文档的数组中搜索用户的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆