How to programmatically modify security rules in F

2019-03-29 12:55发布

问题:

The examples in the firebase documents assume manual update of firebase security rules. How can security rules be modified programmatically to support real-world collaborative applications? In the use case that I am considering, the requirement is for a user to be able to invite other users to collaborate/share selected data and to be able to grant/revoke access to the collaborators. How can this be accomplished with firebase?

回答1:

You actually shouldn't programmatically change your security rules. You should think of them as code and only change them at deploy time.

If what you're trying to do is change what users are actually allowed to do, you should do this by writing security rules that depend on data in your Firebase.

For example, lets say you wanted to restrict access to a piece of data to only users in a specific group. Rather than modifying the security rules everytime the group membership changed, you would simply store the group in Firebase and have your security rules check to see if the current user is in that group before allowing access.

".read" : "root.child('groups').child($groupID).child(auth.userid).exists()"

That way, anytime group membership changes, users will automatically be granted access to the data they should be allowed to see.

For a more complex example of security rules, take a look at the rules.json file in Firefeed.



回答2:

But how would dynamically added datasets be handled?

You would do this by using the child $ node. It looks something like this:

Here is my database

users
- userIDHere
  - name: John Doe
  - whatever: who knows

And you would set rules on each user by doing this:

{
  "rules": {
    "users": {
      "$user": {
        // whatever rules you want here, and you can reference $user to get the user's id.
      }
    }
  }
}

Hope this is what you were asking, and hope this helps!