【问题标题】:Partial write access to document对文档的部分写入权限
【发布时间】:2019-07-16 13:46:03
【问题描述】:

是否可以设置安全规则,以便根据用户角色仅更新某些字段?

考虑一个用户试图编辑以下要编辑的文档:

/tasks/task1
  {
   "id":"task1",
   "description":"anyone can edit this",
   "sensitive_info":"only editor can edit this",
   "very_sensitive_info":"only admin can edit this",
  }
}

这是带有角色的用户集合

/users/user1 { “角色”:“管理员” }

/users/user2 { “角色”:“编辑” }

/users/user3 { “角色”:“任何人” }

 match /tasks/{userId} {
        allow read: if true;
        allow create: if true;
        allow update: if <CONDITION HERE>; // <-WHAT GOES HERE?
}

如何让“sensitive_info”字段只能由 user2 和 user1 编辑,而不能由 user3 编辑?

【问题讨论】:

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


    【解决方案1】:

    写入规则要么允许访问整个文档,要么拒绝访问。因此,乍一看,您似乎无法限制用户可以修改的内容。

    但是您可以通过比较文档之前之后写入操作来实际控制用户可以写入的内容。例如,我的规则中经常有这样的检查:

    allow write: if request.resource.data.creator == resource.data.creator
    

    如果creator 字段未修改,则允许写入操作。

    事实上,这很常见,我有一个辅助函数来处理它:

    function isUnmodified(request, resource, key) {
      return request.resource.data[key] == resource.data[key]
    }
    
    allow write: isUnmodified(request, resource, 'creator');
    

    请注意,一旦您尝试访问不存在的字段,规则就会失败,因此使用 isUnmodified 经常与:

    function isNotExisting(request, resource, key) {
      return !(key in request.resource.data) && (!exists(resource) || !(key in resource.data));
    }
    
    allow write: isNotExisting(request, resource, 'creator') || isUnmodified(request, resource, 'creator');
    

    如果您在正确的范围内定义辅助函数,则无需传递 requestresource 并将整个内容缩短为:

    function isUnmodified(key) {
      return request.resource.data[key] == resource.data[key]
    }
    
    function isNotExisting(key) {
      return !(key in request.resource.data) && (!exists(resource) || !(key in resource.data));
    }
    
    allow write: isNotExisting('creator') || isUnmodified('creator');
    

    【讨论】:

      猜你喜欢
      • 2016-11-14
      • 2022-01-25
      • 1970-01-01
      • 2018-06-27
      • 2011-01-20
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多