Cloud Firestore的自定义安全规则

时间:2018-02-13 12:45:31

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

我想创建一个Cloud Firestore实时数据库,其中包含用户可以加入的组以及向其组的其他成员共享信息。我希望保护用户的匿名性,以便我看到它的实现方式是:

  • 群组创建者生成格式为XXXX-XXXX-XXXX-XXXX
  • 的群组密钥
  • 想要加入的人必须拥有他们在应用中输入的群组密钥,之后他们应该能够阅读创建更新< / strong>该群组中的数据

所以基本上数据结构是这样的:

body {
  background: #f2f2f2;
}
 
.selectdiv {
  position: relative;
  /*Don't really need this just for demo styling*/
  
  float: left;
  min-width: 200px;
  margin: 50px 33%;
}
 
/*To remove button from IE11, thank you Matt */
select::-ms-expand {
     display: none;
}
 
.selectdiv:after {
  content: '<>';
  font: 17px "Consolas", monospace;
  color: #333;
  -webkit-transform: rotate(90deg);
  -moz-transform: rotate(90deg);
  -ms-transform: rotate(90deg);
  transform: rotate(90deg);
  right: 11px;
  /*Adjust for position however you want*/
  
  top: 18px;
  padding: 0 0 2px;
  border-bottom: 1px solid #999;
  /*left line */
  
  position: absolute;
  pointer-events: none;
}
 
.selectdiv select {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  display: block;
  width: 100%;
  max-width: 320px;
  height: 50px;
  float: right;
  margin: 5px 0px;
  padding: 0px 24px;
  font-size: 16px;
  line-height: 1.75;
  color: #333;
  background-color: #ffffff;
  background-image: none;
  border: 1px solid #cccccc;
  -ms-word-break: normal;
  word-break: normal;
}
 

问题是,我应该编写哪些安全规则以允许用户仅在他们所属的群组中读取创建更新数据(有其组密钥)?同时,如何禁止用户查找其他群组&#39;键?

2 个答案:

答案 0 :(得分:2)

您的群组结构可以保持原样 -

groups (Collection) : [
    //groups as documents
    "ABCD-0000-0000-0001" : { /*group data model*/ }
    "ABCD-0000-0000-0002" : { /*group data model*/ }
    "ABCD-0000-0000-0003" : { /*group data model*/ } ]

要维护访问权限,您可以将另一个名为 group_users 集合作为 -

group_users(Collection)/ <group_id>(Document)/ members(Collection)/ :
       uid_1 (document)
       uid_2 (document)    
       ...

现在允许的规则可以像 -

service cloud.firestore {
  match /databases/{database}/documents { 
    match /groups/{group_id} {
        allow read, create, update: if exists(/databases/$(database)/documents/group_users/$(group_id)/members/$(request.auth.uid));
    }
  }
}

当成员加入群组时,您必须将用户的uid添加到该新群集中 -

group_users/<group_id>/members

对于管理员,您可以拥有类似的集合,并在管理员创建组时添加uid -

group_users/<group_id>/admins

除了在groups集合之外设置单独的集合之外,您可以将组内的集合作为替代解决方案,然后您必须更多地修改组数据模型。

同样FYI,安全规则中的每个exists()调用都被计费(可能是一次读取操作)。

here是一份详细的文档,解释了火库安全规则的几乎所有可能方面。

答案 1 :(得分:1)

您可以将组ID保存在用户的个人资料中。然后创建一个规则,该规则仅在该组ID存在时才允许CRU权限。

db.collection.('users').doc({userId}.update({
  ABCD-0000-0000-0001: true
})

match /groups/{groupId} {
  allow read, create, update: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.$(groupId) == true;
}