Firebase Firestore 安全规则共享数据



我在firestore中有这个数据结构,我试图将用户链接到配置文件,然后链接到事件。一个配置文件可以由多个用户共享,并且应该能够访问该配置文件的事件。

user
- id
- email
- name
- profilePicUrl
profile
- id
- name
- dateOfBirth
- owners: [ "user1","user2" ]
- etc.
event
- id
- profileId
- name
- startDate
- endDate

我目前有:

service cloud.firestore {
match /databases/{database}/documents {
match /users/{id} {
allow read, write: if request.auth.uid == id;
}
match /profiles/{id} {
allow read, write: if ("owners" in resource.data && resource.data.owners != null && request.auth.uid in resource.data.owners);
}
match /events/{id} {
allow read, write: if hasAccess(userId, resource) == true;
}
}
}
function hasAccess(userId, resource) {
// Not sure what to put here but basically need
// to get profiles where user is owner
// and get events for these profiles
}

但不确定在hasAccess函数中放什么。如果有人可以指导我,请表示感谢。

更新 2019/10/11

不知何故,我使用以下规则使其工作:

match /events/{id} {
allow read, write: if (exists(/databases/$(database)/documents/profiles/$(resource.data.profileId)) && 
"owners" in get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data && 
get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data.owners != null && 
request.auth.uid in get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data.owners);
}

更新 2019/10/14

我在编写时遇到了一些权限问题,所以我不得不对其进行修改,如下所示:

match /events/{id} {
allow read: if ( exists(/databases/$(database)/documents/profiles/$(resource.data.profileId)) 
&&   "owners" in get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data 
&&   get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data.owners != null 
&&   request.auth.uid in get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data.owners);
allow write: if ( request.auth.uid in get(/databases/$(database)/documents/profiles/$(resource.data.profileId)).data.owners );
}

鉴于数据的现有结构,您尝试执行的操作实际上无法使用安全规则来实现。 这是因为安全规则无法对集合执行查询。 您唯一能做的就是使用其已知路径get()特定文档以读取其字段,这不会帮助您链接无法构建该路径的文档。

相反,您可以做的是将规则所需的数据复制到需要保护的每个文档中。 这意味着每个事件文档都需要将每个所有者列表的副本作为字段。 是的,如果事件的所有者列表必须更改,那么使所有事件保持最新状态会更加麻烦。

最新更新