【发布时间】:2019-06-04 11:17:07
【问题描述】:
这是我现在面临的 Firestore 安全规则问题。
首先,这里是我的 firestore 数据库中的数据结构示例:
userProfiles/userId/userData
companies/companyId/companyData
看起来很简单。每个userData 都包含一个名为companies 的数组,其中包含该用户有权访问的所有companyId。
现在我需要编写规则,仅当 companyId 是特定的用户信息公司列表时才允许读取 companyData。
以下是对我有效的规则:
service cloud.firestore {
match /databases/{database}/documents {
match /companies/{companyId} {
allow read: if companyId in get(/databases/$(database)/documents/userProfiles/$(request.auth.uid)).data.companies
}
}
}
考虑到我将有更多的规则,我想让它们更具可读性和重用性。根据official guide,我可以创建自定义函数,根据article,它们可以是通用的,并且可以在主要规则块之外声明。
我将我的规则重构为如下所示,它对我也有效:
service cloud.firestore {
match /databases/{database}/documents {
match /companies/{companyId} {
allow read: if companyId in getUserCompanies()
}
function getUserCompanies() {
return get(/databases/$(database)/documents/userProfiles/$(request.auth.uid)).data.companies
}
}
}
但现在我想将函数移到规则块之外以使其更加清晰:
service cloud.firestore {
match /databases/{database}/documents {
match /companies/{companyId} {
allow read: if companyId in getUserCompanies()
}
}
}
function getUserCompanies() {
return get(/databases/$(database)/documents/userProfiles/$(request.auth.uid)).data.companies
}
那是行不通的。没有任何错误,我只是收到来自模拟器的常规Read denied 消息。
所以问题是:是否可以像我在示例中所做的那样将函数移到外部?我在这里犯了什么明显的错误吗?有没有更好的方法让我的规则设置更加清晰?
附: 我还尝试将一些参数传递给该函数,包括用户和公司 ID - 不走运。
【问题讨论】:
-
不可能,规则只在它们定义的范围内起作用,他们在这里提到的很微妙firebase.google.com/docs/firestore/security/rules-conditions
-
@andresmijares 这听起来像是一个答案。
-
@andresmijares 这篇文章的这一部分怎么样? fireship.io/snippets/firestore-rules-recipes/#common-functions
-
很难说,可能作者想把它们分开来更好地解释一下
标签: firebase google-cloud-firestore firebase-security