简体   繁体   中英

permission denied on firebase database

I am trying to create a registration activity inside a draft chat application using android studio. At first I am checking if all the fields of the form are filled and then I am at the point where I want to check if the desired username of the user is already inside the database and reject that request with a message.

This is the function I managed to assemble together:

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) {

            }
        });
    }

When I am at the point where I click the register button it gives me an error inside the logcat saying:

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

Its like I dont have access to that specific value of the database.

These are the rules inside the db:

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

I did tried to modify the db rules but it was giving me an error.

I am going to tell the whole story of your code.

you are checking the existing user of before the registration.

but how can you get firebase auth id, before registration? you will get auth id after the registration then only you can check this rules.

// 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"
       }
     }
   }
}

if you want to check the users, you need to modify your your rules as here

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

but i think this is a bad example when you are using firebase auth. you don't have to check the existing users in firebase auth. firebase auth will check it for you. and give you error if user already registered

here is the sample code, be free to modify it

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);
                        }
                    }
                });

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM