swift - 火存储 : Queries and Security (Swift)

标签 swift google-cloud-firestore firebase-security

TL;DR 如何对安全的 Firestore 集合执行查询?

在 Firestore 中具有以下安全规则:

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;
        }    
    }
}

目前,文档ID是userId,每个文档中还有一个带有userId的字段。如果我使用文档 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")
    }
}

但是,如果我随后执行查询并告诉它仅返回 userId 字段与当前登录用户相同的文档,则会失败并出现“缺少或权限不足”安全错误。

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())")
        }
    }
}

那么,如何要求 Firestore 安全地仅查找 userId 字段与登录用户的 userId 匹配的文档?

谢谢。

最佳答案

这有效:

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

关于swift - 火存储 : Queries and Security (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539113/

相关文章:

iOS - Apple 会喜欢 Firebase 吗?

Firebase 规则 : how to restrict access based on user role

ios - 在 Swift 的 TableView 中的每小时日历中创建事件

带有Xcode 11.2.1的swift_initClassMetadataImpl EXC_BAD_ACCESS

swift - 错误的 dispatch 组通知安置?

Swift Firestore 阻止检查字典键是否存在

xcode - OS X 在 swift 中从 xib 添加 subview

firebase - 如何为有状态小部件编写测试?

firebase - 在 FireStore/Document DB 中有效地存储和获得喜欢

firebase - PERMISSION_DENIED:权限不足或不足- flutter