Firebase安全规则限制对子集合的访问

时间:2020-11-03 10:24:55

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

这是我的数据库结构:

用户(集合)->用户文档(uid)->愿望清单(集合)->愿望清单->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)
                }
            }
        }
    }
}

如果用户未被授权,这也应该起作用。其他所有内容应仅限于授权用户。

1 个答案:

答案 0 :(得分: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规则,那里有很多有用的信息。