Firestore Rules to restrict write access to a specific field in a document

人盡茶涼 提交于 2019-12-31 09:44:11

问题


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

Users/{userId}/payments/{document}

each {document} is an object that looks like:

{
  amount: 55
  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;
}

What Firestore Rules will achieve my desired security?


回答1:


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


来源:https://stackoverflow.com/questions/48314542/firestore-rules-to-restrict-write-access-to-a-specific-field-in-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!