0
votes

TL;DR How do you perform a query on a secure Firestore collection?

In Firestore have the following Security Rule:

service cloud.firestore {
    match /databases/{database}/documents {
        match /users/{userId} {
          allow read, update, delete: if request.auth.uid == userId;
          allow create: if request.auth.uid != null;
        }    
    }
}

Currently, the document ID is the userId and there is also a field in each document with the userId. I can find the document if I go straight to a specific document using its document ID:

let docRef = db.collection("users").document(userId)
docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
    } else {
        print("Document cannot be read or does not exist")
    }
}

However, if I then perform a query and tell it to only bring back those documents that the userId field as the same as the currently logged in user it fails with a "Missing or insufficient permissions" security error.

db.collection("users").whereField("userId", isEqualTo: userId).getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
        }
    }
}

So, how do I ask Firestore to securely find only those documents whose userId field matches the logged in user's userId?

Thanks.

1
What about using .whereField(FieldPath(["userId"]), isEqualTo: userId) instead?Guy Kogus
Also, in the rules you can also use allow read, update, delete: if request.auth.uid == request.resource.data.userId;Guy Kogus
@Guy Kogus Using .whereField(FieldPath(["userId"]), isEqualTo: userId) also generates the error "Error getting documents: Error Domain=FIRFirestoreErrorDomain Code=7 'Missing or insufficient permissions.'"David Cittadini

1 Answers

0
votes

This works:

allow read, update, delete: if resource.data.userId == request.auth.uid;