Firestore: Queries and Security (Swift)

不问归期 提交于 2021-02-11 12:29:34

问题


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:


This works:

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


来源:https://stackoverflow.com/questions/50539113/firestore-queries-and-security-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!