[英]permission denied on firebase database
我正在嘗試使用android studio在草稿聊天應用程序中創建注冊活動。 首先,我要檢查表單的所有字段是否都已填寫,然后要檢查用戶所需的用戶名是否已經在數據庫中,並通過消息拒絕該請求。
這是我設法組裝在一起的功能:
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:在/ users上偵聽失敗:DatabaseError:權限被拒絕”
就像我無權訪問該數據庫的特定值。
這些是數據庫內部的規則:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
我確實試圖修改數據庫規則,但它給了我一個錯誤。
我將講述您的代碼的整個故事。
您正在檢查注冊前的現有用戶。
但是如何在注冊之前獲取Firebase身份驗證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身份驗證時,這是一個不好的例子。 您無需在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);
}
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.