Firestore Rules to restrict write access to a spec

2019-03-27 05:52发布

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条回答
爷的心禁止访问
2楼-- · 2019-03-27 06:26

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/{documents} {
        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(); 
    }
  }
}
查看更多
登录 后发表回答