【问题标题】:Firebase Security Rules restrict access to sub collectionsFirebase 安全规则限制对子集合的访问
【发布时间】:2020-11-03 10:24:55
【问题描述】:

这是我的数据库结构:

users (collection) -> user-docs (uid) -> wishlists (collection) -> wishlist-docs -> wünsche -> wünsche-docs

users 应该是 readable,适用于所有人,即使是未经授权的用户。 其他所有内容都应该仅对授权用户可读/可写

这是我尝试过的:

service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
  allow write: if request.auth != null;
}
match /{users} {
    allow read;
}
match /{users}/documents/{allSubcollections=**} {
    allow read: if request.auth != null
}
}
}

但这不起作用,因为read 有问题。我什么也看不懂。我在这里做错了什么?

编辑:

这就是我想要访问users的方式:

//MARK: check username
static func checkUsername(field: String, completion: @escaping (Bool) -> Void) {
    
    let db = Firestore.firestore()
    let collectionRef = db.collection(Keys.users)
    
    collectionRef.whereField(Keys.username, isEqualTo: field).getDocuments { (snapshot, err) in
        if let err = err {
            print("Error getting document: \(err)")
        } else if (snapshot?.isEmpty)! {
            completion(false)
        } else {
            for document in (snapshot?.documents)! {
                if document.data()[Keys.username] != nil {
                    completion(true)
                }
            }
        }
    }
}

如果用户未经授权,这也应该有效。其他一切都应仅限于授权用户。

【问题讨论】:

    标签: ios firebase google-cloud-firestore firebase-security


    【解决方案1】:

    您正在使用{users} 来引用您的集合名称,这是不正确的,您需要简单地使用它而不使用括号,因为它们在您的规则中用作通配符,例如。您可以使用/users/{userId} 来匹配规则中的userId

    此外,我不建议在您的规则开始时对所有集合使用规则,因为它容易出错。话虽如此,以下规则应该适用于您的情况:

    service cloud.firestore {
        match /databases/{database}/documents {
            match /users/{userId} {
                allow read;
                allow write: if request.auth != null;
            }
            match /users/{userId}/wishlists/{restOfPath=**} {
                allow read,write: if request.auth != null;
            }
        }
    }
    

    尝试一下,如果它仍然不起作用,请告诉我。另外,请查看 video tutorial 了解 Firebase 规则,那里有很多有用的信息。

    【讨论】:

    • 感谢您的帮助,但这不起作用。如果没有授权,我不能read用户
    • 尝试编辑后的答案,删除整个通用规则并将其直接应用于用户。
    • 尝试在/users 之后添加/{userID},这表明您正在将规则应用于每个user 文档,我忘记添加了。我不认为问题出在您的代码中,而是 firebase 规则自己。试试这个,让我知道它是否有效。
    • 好吧,所以用户部分正在工作,但现在第二条规则失败了
    • 第二条规则中的documents 是什么?也许这就是问题
    猜你喜欢
    • 2020-02-02
    • 1970-01-01
    • 2020-07-01
    • 2012-12-27
    相关资源
    最近更新 更多