1
votes

We can securely query documents using authenticated user's UID, using firestore rules like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /stories/{storyid} {
      // Only the authenticated user who authored the document can read or write
      allow read, write: if request.auth != null && request.auth.uid == resource.data.author;
    }
  }
}

But I can't find how to fill the data with the authenticated user UID.

The below document is working fine, but it was sent from the client-side, and I don't think it's secure, as the request could have tampered with another user UID.

{
  title: "A Great Story",
  content: "Once upon a time...",
  author: user.uid,
  published: false
}

Basically, I need a user UID value from Firebase server, just like we can insert a timestamp from server with firestore.FieldValue.serverTimestamp()

1

1 Answers

1
votes

I don't think it's secure, as the request could have tampered with another user UID.

By adding the request.auth.uid == request.resource.data.author clause in your write security rule you will guarantee that the request cannot be tampered with another user uid.

This clause verifies that the value of the field author corresponds to the uid of the user executing the write.


More explanations in the doc, here and here as well as here on how the integrity of ID tokens is verified.


Important: Note that we use request.resource.data.author instead of resource.data.author, because, as explained in the doc:

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.

and

the request.resource variable contains the future state of the document.

As a consequence you should most probably separate the read and write rules.