Search code examples
androidfirebase-realtime-databasefirebase-security

Firebase rules in which a user can edit data of another user if he clicked on his profile


I have developed an app using firebase realtime database. In the app, if e-g user 1 clicks on the profile of user 2 then the data of user 2 would be changed. User 1 can only change the data of other users if he clicks on their profiles. I have written some rules to secure my database but these rules won't allow user 1 to change the data of other users if he clicks on their profile. You help will be highly appreciated. Thank You Below is my code: Firebase Rules Firebase Rules Database Structure

My Database structure

Java Code which will change user data if his profile is clicked

  holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               dRef.child(modelClass.get(position).userID).child("showGigCount").setValue(modelClass.get(position).getShowGigCount()-1); // this will decrease showGigCount for clicked users
                dRef.child(modelClass.get(position).getUserID()).child("clicksOnProfile").setValue(modelClass.get(position).getClicksOnProfile()+1); // this will increase clicksOnProfile for clicked users
                dRef.child(modelClass.get(position).getUserID()).child("lifeTimeClicksOnProfile").setValue(modelClass.get(position).getLifeTimeClicksOnProfile()+1); // this will increase clicksOnProfile for clicked users

Solution

  • It sounds like you want to allow certain properties to be modified by all users, which you can do with:

    ...
    "$user_id": {
      ".write": "auth != null && $user_id === auth.uid",
      "showGigCount": {
        ".write": "auth != null"
      },
      "clicksOnProfile": {
        ".write": "auth != null"
      },
      "lifeTimeClicksOnProfile": {
        ".write": "auth != null"
      },
    }
    ...
    

    The added rules give permission to write the lower level properties, while your original write rules on $user_id still rejects writing other properties of the user.