Search code examples
javaandroidfirebase-realtime-databasefirebase-security

i want to get data "createdAt" and "imageURL" for every user but error "Listen at /Users failed: DatabaseError: Permission denied"


I want to retrieve data "createdAt" and "imageURL" for every user who has just registered to RecylerView but is having problems with:

Listen at /Users failed: DatabaseError: Permission denied

DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference(REF_USERS);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -10);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
String dateSevenDaysAgo = dateFormat.format(calendar.getTime());
Query query = databaseRef.orderByChild(EXTRA_CREATED_AT).startAt(dateSevenDaysAgo);
query.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {
            User user = dataSnapshot.getValue(User.class);
            assert user != null;
            userList.add(user);
            userAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {
        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {
        }

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

Firebase Rule enter image description here


Solution

  • Your security rules grant access to /Users/$uid to any logged in user. But your code tries to read from /Users directly, and the rules don't provide anyone read access there.

    If you want to be able to read data with your current security rules, you need to change your code to read data from a specific user.

    If you want to allow your current code to work, you need to allow the user to read the entire /Users node, so move the ".read" rules that you have one level up.

    {
      "rules": {
        "Users": {
          ".read": "auth.uid != null",
          "$uid": {
            ...
          }
        }
      }
    }