【问题标题】:firestore how to check for the doc owner before write?firestore 如何在写入前检查文档所有者?
【发布时间】:2022-11-25 06:16:35
【问题描述】:
在允许用户创建之前如何检查文档所有者?
脚步:
- 文档已由同一所有者创建。
- 之后,同一所有者将尝试在文档中创建属性和值。
document.owner发布时报错。
//only allow create in moviesCommentID/{document} when document is owned by the user
match /moviesCommentID/{document=**} {
allow create: if request.auth != null && document.owner == request.auth.uid;
}
任何帮助是极大的赞赏。
【问题讨论】:
标签:
firebase
google-cloud-firestore
firebase-authentication
rules
【解决方案1】:
1- 创作
您需要在您要更改的存储所有者 uid 的 Firestore 文档中有一个字段
allow create: if request.auth != null && resource.data.ownerUid == request.auth.uid;
2-更新:
使用与“创建”相同的方法(所有者实际上是登录的人),但还要添加一些内容来说明他们不能将所有者更改为另一个用户
allow update: if request.resource.data.ownerUid== resource.data.ownerUid;
请注意,request.resource 变量包含文档的未来状态
【解决方案2】:
规则中的 document 变量是一个以文档 ID 作为值的字符串。
Firestore 没有任何文档所有者的内置概念。但是,如果您在文档数据中有一个 owner 字段,您可以在您的规则中以 resource.data.owner 的形式访问它。另请查看data validation in security rules 上的 Firebase 文档。