swiftgoogle-cloud-firestorefirebase-security

Firestore rule for single document


I have a Firestore database with the following rule:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null && request.auth.uid == resource.data.uid;
      allow create: if request.auth != null && request.auth.uid == request.resource.data.uid;
    }
  }
}

Here is my collection: enter image description here

When querying for a set of documents, I need to include the uid in the query to satisfy the rule and it works:

try await db.collection("Stocks")
    .whereField("uid", isEqualTo: user.uid) // Include the uid for passing the rule
    .getDocuments()

However, for a single document query for a document that doesn't exist in the database, it returns permission error:

let document = try await db.collection("Stocks")
    .document(stock.id) // The document does not exist in the database
    .getDocument()

if document.exists {

} else {

}

enter image description here

How can I define the rule for this case?


Solution

  • Rule for single document should be:

    allow read: if request.auth != null && 
        (request.auth.uid == resource.data.uid
            || !exists(/databases/$(database)/documents/$(document)));
    

    It allow to read when the document doesn't exit in the database.