Michel
Michel

Reputation: 11755

Security Rules with Firebase

I have been using Firebase for a little while in a project under development, but haven’t worried too much about security up to now. From now on I would like to implement a few Security rules. I have read the QuickStart tutorial on the subject on Firebase web site, but I am not yet sure how it all fits together.

Here the structure of my data:

myApp
- DataList
    - Contents
        - randomKey_One
            value: "grgrsgs;jj…data…data.."
        - randomKey_Two
            value: "43efdsd7gs;jj…data…data.."
        - randomKey_Three
            value: "8dfsvshj…data…data.."
        …….
    - Names
        - randomKey_One
            - authorID: "PeterLogID"
            - name: "RecordOne_Peter"
        - randomKey_Two
            - authorID: "JohnLogID"
            - name: "RecordStar_byJohn"
        - randomKey_Three
            - authorID: "PeterLogID"
            - name: "RecordTwo_Peter"
        …….

There is a one-to-one correspondance between Contents and Names, which is established through the values of randomKey_One, randomKey_Two, ….etc.. Those keys are automatically generated when a new record is created. I store the login ID of the user in the Names section, in the authorID field.

What I want is:

1) To have read access for the whole world to all the data (possibly with the exception of authorIDs).
2) To give write(and delete) access to a record, only if the authorID field matches auth.uid (i.e. the logged in user).

I have already figured out part 1), forgetting the “exception of authorIDs”. How do I go with part 2)? What I have tried at this point did not work. One issue I have is that I don’t know how to access the authorID field within the security rule script, since I do not have the name of its parent.

Upvotes: 0

Views: 199

Answers (1)

Michel
Michel

Reputation: 11755

For those who may one day hit the same problem and read this. Here I put the solution I came up with, after a few hours. Since this is my first time to deal with Firebase Security Rules, any expert on the subject is welcome to comment.

{
    "rules": {
      ".read": true,
      "DataList": {
        "Names": {
          "$Name": {
             ".write": "newData.child('authorID').val() === auth.uid || data.child('authorID').val() === auth.uid"
          }
        },
        "Contents": {
          "$Content": {
            ".write": "root.child('DataList/Names/'+$Content).exists() && root.child('DataList/Names/'+$Content).child('authorID').val() === auth.uid"
          }
        }
      }
    }
}

Upvotes: 1

Related Questions