Search code examples
google-cloud-firestorefirebase-security

how do you access a variable in a firebase document in the security rules?


I am trying to do firebase security rules in firestore, and I want to allow users to write data to the "posts" collection if the current users id (request.auth.uid is equal to the "uid" in my "posts" collection.

Here is a picture of my firebase collection. I want to access the "uid" variable in the "posts" collection.enter image description here

Here is what I have so far in my security rules: enter image description here

Thank you in advance! Very much appreciated!


Solution

  • You can access the current (pre-write) data of the document through resource.data, and the updates (post-write if the write is allowed) as request.resource.data.

    So to access your UID field, that'd be resource.data.uid or request.resource.data.uid respectively.

    For more on this, see the Firebase documentation on data validation in security rules, on fixing open access rules, and on restricting updates to certain fields.