I am building a simple Firebase application with AngularJS. This app authenticates users through Google. Each user has a list of books. Anyone can see books, even if they are not authenticated. Only the creator of a book can edit it. However, individual users need to be able to record that they've read a book even if someone else added it.
I have rules.json like so:
{
  "rules": {
    ".read": false,
    ".write": false,
    "book": {
      "$uid": {
        ".write": "auth !== null && auth.uid === $uid",
      }
      ".read": true,
    }
  }
}
And I am trying to write a book simply with:
$firebaseArray(new Firebase(URL + "/book")).$add({foo: "bar"})
I get a "permission denied" error when trying to do this although I do seem to be able to read books I create manually in Forge.
I also think that the best way to store readers would be to make it a property of the book (a set of $uid for logged-in readers).  ".write" seems like it would block this, so how would I do that?
"$uid": {
  ".write": "auth !== null && auth.uid === $uid",
  "readers": {
    ".write": "auth !== null"
  }
},
It seems like a validation rule would be appropriate here as well ... something like newData.val() == auth.uid, but I'm not sure how to validate that readers is supposed to be an array (or specifically a set) of these values.
                        
Let's start with a sample JSON snippet:
So this is a list with two links to articles. Each link was added by a different user, who is identified by
creator. The value ofcreatoris auid, which is a value that Firebase Authentication provides and that is available in your security rules underauth.uid.I'll split your rule into two parts here:
As far as I see your
.readrule is correct, since your ref is to the /book node.Note that the ref below would not work, since you don't have read-access to the top-level node.
Now for the
.writerules. First off is that you'll need to grant users write-access on thebooklevel already. Calling$addmeans that you're adding a node under that level, so write-access is required.I leave the
.readrules out here for clarity.This allows any authenticated user to write to the book node. This means that they can add new books (which you want) and change existing books (which you don't want).
Your last requirement is most tricky. Any user can add a book. But once someone added a book, only that person can modify it. In Firebase's Security Rules, you'd model that like:
In this last rule, we allow writing of a specific book if either there is no current data in this location (i.e. it's a new book) or if the data was created by the current user.
In the above example
$bookidis just a variable name. The important thing is that the rule under it is applied to every book. If needed we could use$bookidin our rules and it would hold-JRHTHaIs-jNPLXOQivYor-JRHTHaKuITFIhnj02kErespectively. But in this case, that is not needed.