Firestore:查询和安全性(快速) [英] Firestore: Queries and Security (Swift)

查看:62
本文介绍了Firestore:查询和安全性(快速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

当前,文档ID是userId,并且每个文档中还有一个带有userId的字段.如果我直接使用特定文档的文档ID来查找该文档,则可以找到该文档:

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

但是,如果我随后执行查询并告诉它仅带回那些文档,即userId字段与当前登录的用户相同,则会失败,并显示缺少权限或权限不足"安全错误.

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

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

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

谢谢.

推荐答案

这有效:

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

这篇关于Firestore:查询和安全性(快速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆