gpt4 book ai didi

java - firebase 数据库的权限被拒绝

转载 作者:行者123 更新时间:2023-12-02 03:28:01 24 4
gpt4 key购买 nike

我正在尝试使用 android studio 在草稿聊天应用程序中创建注册 Activity 。首先,我检查表单的所有字段是否已填写,然后我想检查用户所需的用户名是否已在数据库中,并通过消息拒绝该请求。

这是我设法组装在一起的函数:

private void checkifUsernameExists(final String username, final String email, final String password) {
Query usernameQuery = FirebaseDatabase.getInstance().getReference().child("users").orderByChild("username").equalTo(username);
usernameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(registerActivity.this, "Username already exists", Toast.LENGTH_LONG).show();
} else {
message.setTitle("Registering user");
message.setMessage("Pleases wait while we create your account");
message.setCanceledOnTouchOutside(false);
message.show();
registerUser(username, email, password);
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});
}

当我点击注册按钮时,logcat 内出现错误说:

"W/SyncTree: Listen at /users failed: DatabaseError: Permission denied"

就像我无权访问数据库的特定值一样。

这些是数据库内的规则:

{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}

我确实尝试修改数据库规则,但它给了我一个错误。

最佳答案

我将讲述您的代码的整个故事。

您正在检查注册前的现有用户。

但是在注册之前如何获得 firebase auth id?注册后您将获得身份验证ID,只有您可以查看此规则。

// Checks auth uid equals database node uid
// In other words, the User can only access their own data

{
"rules": {
"posts": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}

如果您想检查用户,您需要按照此处修改您的规则

{
"rules": {
"posts": {
"$uid": {
".read": true,
".write": "$uid === auth.uid"
}
}
}
}

但我认为当您使用 firebase auth 时这是一个不好的例子。您不必检查 firebase auth 中的现有用户。 firebase auth 将为您检查。如果用户已经注册,则会出现错误

这里是示例代码,可以随意修改

private void signUpInFirebaseAuth(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign up success, update UI with the signed-up user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
saveUserCredentials(user.getUid(), password, email);
}
updateUI(user);
} else {
// If sign up fails, display a message to the user.
Log.e(TAG, "createUserWithEmail:failure", task.getException());
//Toast.makeText(UserRegistrationActivity.this, "Sign Up Failed!: "+task.getException().getMessage(), Toast.LENGTH_LONG).show();

updateUI(null);
}
}
});

}

关于java - firebase 数据库的权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com