简体   繁体   中英

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: "xyz@gmail.com"
    

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

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.

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()"
  ...
}

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