【问题标题】:Firestore rules - use exists with whereFirestore 规则 - 与 where 一起使用
【发布时间】:2019-07-16 08:31:35
【问题描述】:

在我的项目中,我有用户和类的 firestore 集合。每个用户可以是一个或多个类的一部分。 Classes 文档具有属性成员,它是一个数组,包括该类中的所有用户 uid。

例如:

users documents:
doc.id: USER1UID
{ name: 'user1', email: 'user1@user1.com', phone: '+123 456 789 001' }

doc.id: USER2UID
{ name: 'user2', email: 'user2@user2.com', phone: '+123 456 789 002' }

doc.id: USER3UID
{ name: 'user3', email: 'user3@user3.com', phone: '+123 654 789 003' }

classes documents:
doc.id: ABCDEF
{ name="class1", members: ['USER1UID', 'USER2UID'] }

doc.id: GHIJKL
{ name="class2", members: ['USER1UID', 'USER3UID'] }

doc.id: MNOPQR
{ name="class3", members: ['USER3UID'] }

我需要编写一个规则,该规则仅允许用户阅读有关另一个用户的详细信息,前提是他们在同一个班级。每个用户还可以阅读自己的个人资料。

在这种情况下,user1 可以读取 user2 和 user3 的详细信息。 (他们在 class1 和 class2 中)。 User2 只能读取 user1 的详细信息(它们在 class1 中)。 User3 只能读取 user1 的详细信息(他们在 class2 中)。

我需要类似的东西:

match /users/{userId} {
   allow read: 
     //user is logged in
     if request.auth != null 
     && (
            //user can read own profile
            request.auth.id == $(userId)

            //there is a class where are both (requesting and requested) users
            || exists( (/databases/$(database)/documents/classes/).where(request.auth.id in members).where($(userId) in members)
        )
}

【问题讨论】:

    标签: google-cloud-firestore firebase-security


    【解决方案1】:

    您的数据库架构无法实现您尝试执行的操作,因为安全规则不允许您执行查询。您一次只能使用其已知路径请求一个文档,每个规则执行最多 10 个文档。

    您可以做的是管理每个用户文档以包含与该用户具有共同类的所有其他用户的列表。但是你必须编写一些代码来保持最新,因为课程名册可能会随着时间而改变。这可能是 Cloud Functions 的一个很好的用途。

    【讨论】:

    • 谢谢道格。从安全的角度来看,这是一种风险,因为用户可以编辑自己的配置文件,从而将其他用户添加到列表中。因此,我可能不得不再创建一个只能从 firebase admin SDK 写入的集合(规则中的“if false”)并使用 firestore 触发器更新列表。对于这种简单的用例,解决方案相当困难(且昂贵)。有没有其他方法可以实现这一目标?也许禁用直接 DB 读取并使用 Cloud Functions 读取、检查和返回数据?还是切换到实时数据库?
    • 当然,您可以通过 Cloud Functions 强制所有请求。我不认为改变数据库产品会有帮助。
    猜你喜欢
    • 2019-01-26
    • 1970-01-01
    • 2021-09-11
    • 2021-11-15
    • 1970-01-01
    • 2019-01-31
    • 2019-12-14
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多