Search code examples
androidfirebase-realtime-databasefirebase-security

how to validate firebase rule with boolean value?


I have set rules in firebase to validate is admin or not, here is the rule

"rules": {
  "Users": {       
    "$uid": {
      ".read": "auth != null && $uid === auth.uid ||
               (root.child('Users').child('$uid').child('admin').val() == true)",
      ".write": "auth != null && $uid === auth.uid || 
               (root.child('Users').child('$uid').child('admin').val() == true)",
    }
  }
}

The problem is that I am trying to read and write from Admin app, but I am unable to read and write from app as I have tried like this can any please help me to find out the solution....?

myViewHolder.paid.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
        reference.child(getRef(position).getKey()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String postKey = getRef(position).getKey();

                if (snapshot.exists()) {
                    Boolean isadmin = (Boolean) snapshot.child("admin").getValue();
                    if (isadmin == true) {

                        reference.child(postKey).child("adminScores").setValue(0);
                        Toast.makeText(view.getContext(), "Updated", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(view.getContext(), "No such data", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(view.getContext(), "data not found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(view.getContext(), "Errors", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

Here is my database stracture,

enter image description here

I want the solution that how could I fetch data from firebase Realtime database and after fetching data from firebase how could I check, read and write data into database....


Solution

  • The problem is the child('$uid') in this code:

    (root.child('Users').child('$uid').child('admin').val() == true)
    

    The '$uid' here is just a literal string, while you want it to be the value of the uid variable. To use that value, don't put quotes around $uid:

    (root.child('Users').child($uid).child('admin').val() == true)
    

    Also see the Firebase documentation on wildcard capture variables.