Aisha Kumari
Aisha Kumari

Reputation: 193

how can I read and write as an admin even if the rules set to false in Firebase Realtime Database

As an admin I am trying to get the users data so that I could 'read' and 'write' even through the rules of the firebase 'read','write' set to be false.

users
  |
  "uid"
    |-firstname: "xyz"
    |-lastname: "xyz"
    |-email: "[email protected]"
    

Here, is my rules

 "users": {      
 "$uid": {
    ".read": "auth != null && $uid === auth.uid",
        ".write": "auth != null && $uid === auth.uid"
        }
  }

when I am retrieving users data from firebase using FirebaseRecyclerOptions, users data display only when I set rules read and write to true but I want even if the rules set to be false through admin I could read and write. Is this possible

  FirebaseRecyclerOptions<Model> options =
            new FirebaseRecyclerOptions.Builder<Model>()
                    .setQuery(FirebaseDatabase.getInstance().getReference("Users"), Model.class)
                    .build();

Upvotes: 1

Views: 815

Answers (2)

Omer
Omer

Reputation: 51

Add a boolean to your user object and call it admin, set it false for all the users except you.

Now copy that to your firebasee rules:

"users": {      
   ".read": 
      "root.child('users').child($uid).child('Admin').val()",            
   ".write":"  
      "root.child('users').child($uid).child('Admin').val()"

 ,"$uid": {
    ".read": "auth != null && $uid === auth.uid",
        ".write": "auth != null && $uid === auth.uid"
        }
   }

}                
}

1

Just like the isActivated boolean I have in my Users you can create a boolean called isAdmin.Add it to your admin class , give it set and get methods in your class.When you upload it to firebase you can read and write this data. Then let your firebase rules to do the job.

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 598916

It depends on what "as an admin" means to you. If the application administrator is only you for example, you could simply hard-code your own UID in the security rules:

"users": {
  ".read": "auth.uid === 'yourOwnUid'"
  "$uid": {
    ".read": "auth != null && ($uid === auth.uid",
    ".write": "auth != null && $uid === auth.uid"
  }
}

This grants the one user access to all of /users, while everyone else can only read their own child node under that path.

Hard-coding the UID like this works great during development, as you're likely the only administrator. Later on when closer to release, you'll want to store a list of administrator UIDs in the database:

"Admins": {
  "yourOwnUid": true,
  "otherUid": true
}

You can then check in your rules whether the current user's UID exists in this path with:

"users": {
  ".read": "root.child('Admins').child(auth.uid).exists()"
  ...
}

Upvotes: 2

Related Questions