在我的数据库中,我有一个包含来自各个用户的文档的集合。每个文档都有一个
user
属性,其值是用户的电子邮件。 (稍后我会将其更改为 userID。)
我想确保用户只能读取、更新和删除用户电子邮件 (request.auth.token.email) 与 user
属性的值匹配的文档。
我花了几个小时试图找到解决方案。我认为这是我最好的方法,但它不起作用:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if isSignedIn() && emailVerified();
}
match /fooCollection/{document} {
allow create: if isSignedIn() && emailVerified() && userValueIsNotManipulated();
allow update, delete: if isSignedIn() && emailVerified() && isOwner() && userValueIsNotManipulated();
allow read: if isSignedIn() && emailVerified() && isOwner();
}
/// Functions ///
function isSignedIn() {
return request.auth != null
}
function emailVerified() {
return request.auth.token.email_verified
}
function isOwner() {
return request.auth.token.email == resource.data.user
}
function userValueIsNotManipulated() {
return request.resource.data.user == request.auth.token.email
}
}
}
我也尝试过:
match /fooCollection/{user}
match /fooCollection/{user} {
...
...
allow read: if isSignedIn() && emailVerified() && request.auth.token.email == user;
}
match /fooCollection/{user}/{document=**}
match /fooCollection/{document}/{user}
我有第二个具有类似数据结构的集合。在我的项目的当前状态下,我向 firestore 发出请求以获取 fooCollection。然后,我在本地过滤用户的文档。对第二个集合的请求以相同的方式工作。因此,我预计我对第一个集合的请求会因上述安全规则而失败,而对第二个集合的请求将在很大程度上起作用。到目前为止,在我的尝试中,要么两个请求都成功,要么两个请求都失败。
那么,我如何确保用户只能读取、更新和删除用户电子邮件 (request.auth.token.email) 等于属性值的文档
user
?
安全规则允许规则重叠。 “一个文档可能会匹配多个匹配语句。在多个允许表达式与一个请求匹配的情况下,如果任何一个条件为真,则允许访问” 看起来这个语句将允许任何读取或写入,并且将覆盖第二个匹配语句。
match /{document=**} {
allow read, write: if isSignedIn() && emailVerified();
}
由于两个匹配语句都使用相同的条件,因此它始终为 true 或始终为 false。