Cloud Firestore安全规则-仅允许写入文档中的特定密钥 [英] Cloud Firestore Security Rules - only allow write to specific key in document

查看:95
本文介绍了Cloud Firestore安全规则-仅允许写入文档中的特定密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Firestore数据库为我的应用程序编写一些规则. 当前,每个人都可以读取数据,经过身份验证的用户可以写入.

I'm currently writing some rules for my app with a Firestore database. Currently everyone can read data and authenticated users can write.

  match /quizzes/{quizId} {
    allow read; 
    allow write: if request.auth != null;
  }

这很好,但是我也希望未经身份验证的用户只写文档中的特定键.

That works fine, but I also want unauthenticated users to write only to a specific key in a document.

文档内容示例:

{
  title: 'title',
  plays: 12,
  playedBy: [//Filled with user id's],
  ...
}

有什么方法可以限制未经身份验证的用户仅具有对playBy数组的写入权限,而不具有对该文档的其他键的写入权限?

Is there any way that limits unauthenticated users to only have write access to the playedBy array and not the other keys of that document?

推荐答案

当然.但是,如果您有很多字段,可能会涉及到一些问题.

Sure thing. But it may become a bit involved if you have a lot of fields.

让我们从最简单的示例开始.这样的事情允许未经身份验证的用户编写playedBy,只要这是文档中的唯一字段即可:

Let's start with the simplest example. Something like this allows an unauthenticated user to write the playedBy as long as that is the only field in the document:

if request.auth != null || request.resource.data.keys().hasOnly(['playedBy'])

如果未经身份验证的用户正在创建新文档或更新现有文档,则此方法有效.但是,一旦文档包含更多字段,它将立即停止,因为request.resource.data包含了写入成功后文档将拥有的所有字段.

This works if the unauthenticated user is creating a new document, or updating an existing one. But it will stop as soon as the document contains more fields, since request.resource.data contains all fields the document will have after the write succeeds.

因此更好的选择是检查仅修改了playedBy,并且所有其他字段都具有与以前相同的值.棘手的一点是处理字段的不存在,我通常使用一些辅助函数来处理这些字段:

So the better alternative is to check that only the playedBy is modified, and that all other fields have the same value as before. The tricky bit there is handling the non-existence of fields, which I typically handle with a few helper functions:

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));
}

然后:

if request.auth != null &&
  request.resource.data.keys().hasOnly(['title', 'plays', 'playedBy']) &&
  isUnmodified('title') && 
  isUnmodified('plays')

确切的规则可能有点过时,但是我希望这足以让您自己完成.

The exact rule might be a bit off, but I hope this is enough to allow you to complete it yourself.

这篇关于Cloud Firestore安全规则-仅允许写入文档中的特定密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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