尝试为Android firestore app启用安全角色
遵循此文件:https://firebase.google.com/docs/firestore/solutions/role-based-access
service cloud.firestore {
match /databases/{database}/documents {
match /Dairy/{dairyId} {
function isSignedIn() {
return request.auth != null;
}
function getRole() {
//both of the below statements are not working
//return resource.data.roles[request.auth.uid];
return get(/databases/$(database)/documents/Dairy/$(dairyId)).data.roles[request.auth.uid];
}
function isOneOfRoles(array) {
return isSignedIn() && (getRole() in array);
}
function isValidNewDoc() {
return resource.data == null
&& request.resource.data.roles[request.auth.uid] == 'OWNER';
}
allow write: if isValidNewDoc() || isOneOfRoles(['OWNER']);
allow read: if isOneOfRoles(['OWNER', 'ADMIN']);
match /{document=**} {
allow read: if isOneOfRoles(['OWNER', 'ADMIN']);
}
}
match /DairyOwnerProfile/{user_profile} {
function isUserSignedIn() {
return request.auth != null;
}
function isValidNewProfile() {
// Valid if Dairy does not exist and the new Dairy has the correct owner.
return isUserSignedIn() && resource.data == null
&& request.resource.data.uid == request.auth.uid;
}
allow read, write: if isUserSignedIn() && (user_profile == request.auth.uid || isValidNewProfile());
}
}
}
域模型
创建文档适用于以下文档模型 与路径 /数据库/ {数据库} /文档/ DairyOwnerProfile / {USER_ID}
public class DairyOwnerProfile {
private String uid;
private String name;
private String phone;
private String dairyId;
}
但是创建并阅读不适用于Dairy集合及其所有子集合 在路径下的商店的乳制品模型 /数据库/ {数据库} /文档/乳品/ {dairyId}
public class Dairy {
private String id;
private String dairyName;
private boolean active;
private String address;
private Date updateTime;
private Map<String, Role> roles;
}
public enum Role {
OWNER, FARMER, ADMIN, MANAGER
}
尝试了几天,但无法弄清楚上述火库安全规则的错误
尝试使用以下变体的isValidNewDoc()方法
//Not working
function isValidNewDoc() {
return resource.data == null
&& request.resource.data.roles[request.auth.uid] == 'OWNER';
}
//Not working
function isValidNewDoc() {
return resource.data == null
&& request.resource.data == null;
}
//Not working
function isValidNewDoc() {
return resource.data == null
&& request.resource.data != null;
}
//Not working
function isValidNewDoc() {
return resource.data == null;
}
//working
function isValidNewDoc() {
return isSignedIn();
}
//Working, Create and update both worked (Sub collection read/write failed)
//but this allows overwriting existing document by another user, adding "resource.data == null" with && causing it to fail
function isValidNewDoc() {
return request.resource.data.roles[request.auth.uid] == 'OWNER';
}
这是Android studio控制台中出现的错误 com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED:权限丢失或不足。
我做错了数据的规则或层次是问题
在Dairy集合下有许多子集合,对这些子集合的读/写也失败
此问题阻止我的第一个版本的Android App发布,请指出我正确的方向找到并解决问题
注意:这是我第一次使用android和firestore
如果需要更多信息,请告诉我。
答案 0 :(得分:2)
使用resource == null
代替resource.data == null
:
function isValidNewDoc() {
return resource == null
&& request.resource.data.roles[request.auth.uid] == 'OWNER';
}