firebase – Firestore安全性 – 仅允许已知字段

我无法弄清楚如何在Firestore中正确设置’.validate’规则.
基本上,我想允许用户文档只包含我知道的字段:

user {
 name: "John"
 phone: "2342222"
 address: "5th Avenue"
}

我不想要除上面3之外的任何其他字段(姓名,电话,地址).

这些字段不会同时保存.姓名和电话将被保存,地址将仅在用户想要编辑他的个人资料时保存.

我已经尝试过以下规则,但似乎不起作用:

allow read: if request.auth.uid == uid;
allow write: if request.auth.uid == uid && 
 request.resource.data.keys() in ["name", "phone", "address"]

感谢帮助.

您可以将规则分开以包含不同的创建和更新(以及删除)逻辑:

// allows for creation with name and phone fields
allow create: if request.resource.data.size() == 2
              && request.resource.data.hasAll(['name', 'phone'])
              && request.resource.data.name is string
              && request.resource.data.phone is string;
// allows a single update adding the address field
// OR (||) in additional constraints
allow update: if request.resource.data.size() == resource.data.size() + 1
              && !('address' in resource.data)
              && request.resource.data.address is string;
相关文章
相关标签/搜索