在android应用程序中,我创建了一个通过电话号码验证的firebase用户,它工作正常然后我更新此用户添加显示名称,这也很好;最后我想将用户的数据保存到firebase数据库中,所以我写了这条规则:
"users" : {
"$user_id" : { // firebase user uid
".read" : "$user_id === auth.uid",
".write" : "$user_id === auth.uid",
".validate": "newData.hasChildren(['enabled', 'group', 'name'])",
"enabled" : { ".validate" : "newData.isBoolean()" },
"group" : { ".validate" : "newData.isString()" },
"name" : { ".validate" : "newData.isString()" },
}
}
这不起作用,我得到“权限被拒绝”,尽管模拟器显示一切正常(在模拟中我使用自定义身份验证并将firebase设置为提供者和用户的uid)。
用户的课程是:
public class User {
public boolean enabled;
public String group;
public String name;
public User() { }
public User(boolean enabled, String group, String name) {
this.enabled = enabled;
this.group = group;
this.name = name;
}
}
我尝试通过以下方式保存:
private void saveUserToDB() {
User newUser = new User(true, "operators", currentUser.getDisplayName());
mRootRef.child("users").child(currentUser.getUid()).setValue(newUser, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.e("ERROR", "Data could not be saved " + databaseError.getMessage());
} else {
Log.e("SUCCESS", "Data saved successfully.");
}
}
});
}
有人可以帮助我理解为什么会这样吗? 感谢
更新 下面是数据库应该如何的“架构”:
{
"messages" : {
"1763409620982" : { // timestamp
"position" : "position text",
"sender" : "sender name",
"text" : "message text"
},
"1763409734527" : { // timestamp
"position" : "position text",
"sender" : "sender name",
"text" : "message text"
}
...
},
"users" : {
"Yi79w0HgA4ZTNAMHadixzoO5PaR2" : { // firebase user uid
"enabled" : true,
"group" : "group 1",
"name" : "user display name"
},
"kX22c0GgL4ZTNAMHallfgoO4pBN1" : { // firebase user uid
"enabled" : true,
"group" : "group 2",
"name" : "user name"
}
...
}
}
这是完整的规则集:
{
"rules": {
"messages" : {
".read" : "root.child('users').child(auth.uid).child('group').val() === 'group 1'",
".write" : "root.child('users').child(auth.uid).child('group').val() === 'group 2'",
"$tstamp" :{
".validate": "newData.hasChildren(['position', 'sender', 'text'])",
"position" : { ".validate" : "newData.isString()" },
"sender" : { ".validate" : "newData.isString()" },
"text" : { ".validate" : "newData.isString()" },
}
},
"users" : {
"$user_id" : {
".read" : "$user_id === auth.uid",
".write" : "$user_id === auth.uid",
".validate": "newData.hasChildren(['enabled', 'group', 'name'])",
"enabled" : { ".validate" : "newData.isBoolean()" },
"group" : { ".validate" : "newData.isString()" },
"name" : { ".validate" : "newData.isString()" },
}
}
}
}
关于用户的类,如上所述,仅用于方法 saveUserToDB