Firestore rules for document field

前端 未结 2 1432
南方客
南方客 2020-12-17 14:40

I\'m struggling within Firestore to set security rules for a document. With the RTDB is was possible to set rules for a specific object property and I\'m trying to do the sa

2条回答
  •  無奈伤痛
    2020-12-17 15:16

    Looks like this is now supported:

    service cloud.firestore {
      match /databases/{database}/documents {
        // Allow the user to read data if the document has the 'visibility'
        // field set to 'public'
        match /cities/{city} {
          allow read: if resource.data.visibility == 'public';
        }
      }
    }
    

    The resource variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.


    To give a concrete example, in my case I needed to provide read access to a group only if the requesting user is in the members field (which is an array) of the groups collection. So I did this:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        function isMember(userId) {
          return (userId in resource.data.members);
        }
        match /groups/{group} {
          allow read: if request.auth != null && isMember(request.auth.uid);
        }
        //...
      }
    }
    

提交回复
热议问题