Firestore规则,用于限制对文档中特定字段的写访问 [英] Firestore Rules to restrict write access to a specific field in a document

查看:67
本文介绍了Firestore规则,用于限制对文档中特定字段的写访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Stripe付款.为此,我在Firestore中具有以下数据模型:

I am using Stripe for payments. For this, I have the following data model in Firestore:

Users/{userId}/payments/{document}

每个{document}是一个看起来像这样的对象:

each {document} is an object that looks like:

{
  amount: 55
  token: {...}
  charge: {...}
}

用户必须能够编写token字段(这是传递给服务器的内容),但是我不希望用户能够编写charge字段.

Users must be able to to write the token field (this is what gets passed to the server), but I don't want users to be able to write the charge field.

目前,我的规则允许任何用户读写此文档:

Currently my rules allow any user to read and write to this document:

match /payments/{documents} {
  allow read, write: if request.auth.uid == userId;
}

哪些Firestore规则可以实现我想要的安全性?

What Firestore Rules will achieve my desired security?

推荐答案

我相信以下内容会起作用,它使客户可以更新除费用以外的其他字段,以及创建不包含费用字段的文档.

I believe something along the following would work, it allows clients to update fields except for charge, as well as create documents that don't have the charge field.

service cloud.firestore {
  match /databases/{database}/documents {
    function valid_create() {
        return !(request.resource.data.keys().hasAll(["charge"]));
    }

    function valid_update() {
        return request.resource.data.charge == resource.data.charge
               || (valid_create()
                  && !(resource.data.keys().hasAll(["charge"])))
    }

    match /payments/{userId} {
        allow read: if request.auth.uid == userId;
        allow create: if request.auth.uid == userId
                        && valid_create(); 
        allow update: if request.auth.uid == userId
                        && valid_update(); 
    }
  }
}

这篇关于Firestore规则,用于限制对文档中特定字段的写访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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