frank timmon
frank timmon

Reputation: 37

Write Rules for ChildByAutoID in Firebase Realtime Database?

JSON:

  "people" : {
    “user uid” : {
      “**Domain** : "aol.com",
      "peopleWhoLike: {
        "-M-vZavBdcpX3SzkvgKN" : "**IrrBgFY9C1ekMmHUkQRzc5LhbDu1**", ////this is autokey: uid of the likeR///
    }
  }

Let us say you want to evaluate IrrBgFY9C1ekMmHUkQRzc5LhbDu1. If he were not proceeded by childByAutoID, I'd use this:

,"peopleWhoLike" : {
"$peopleWhoLike_id": {
    ".read": "auth.uid != null",
    ".write": "$peopleWhoLike_id == auth.uid && data.parent().parent().child('domain').val() == data.parent().parent().parent().child(newData.val()).child('domain').val()"
} /////checks domain of like with domain of person he likes, and makes sure only he can write for himself.

This would be fine if IrrBgFY9C1ekMmHUkQRzc5LhbDu1 stood without the ChildByAutoID, however it does not. So now I am thinking I need to use something like $ChildByAutoID, but am not sure what to call it because it is not explicitly defined in the JSON.

Source for security rules I read through for $ variables: https://firebase.google.com/docs/database/security/rules-conditions

Upvotes: 1

Views: 80

Answers (2)

Jay
Jay

Reputation: 35648

I am adding another answer that specifically addresses the rules part of the question

The goal is to only allow a write to a people node if the domain in that node matches the current users domain node. I won't write all of the rules but this will be the first step:

The structure would be

people
   uid_0
      domain: "aol.com"
   uid_1
      domain: "gmail.com"
users
   uid_2
      domain: "aol.com"
   uid_3
      domain: "aol.com"

The rules would be something like

{
  "rules": {
    ".read": false,
      ".write": false,
        "people": {
          "$uid": {
            ".read": "auth != null",
            ".write": "root.child('people').child($uid).child('domain').val() === 
                       root.child('users').child(auth.uid).child('domain').val()" 
          }
        }
  }
}

The write will be allowed if the value at /people/uid_x/domain = /users/this_uid/domain

With the above structure, users uid_2 and uid_3 can write to people/uid_0 but not to people/uid_1

Upvotes: 1

Jay
Jay

Reputation: 35648

There's no reason to childByAutoId within peoplWhoLikeMe in this use case, and it further complicates the rules.

You know the specific data you want to store, so just store that data with a placeholder for the value.

In other words, I assume you're storing users UID's so your structure would be

people
   this_users_uid
      domain: "aol.com"
      people_who_like_me
          uid_0: true
          uid_3: true

That simplifies the rules dramatically as when another user writes to the people_who_like_me node, just validate the key being written is their own uid. It also guarantees uniqueness so child nodes are never duplicated.

Upvotes: 0

Related Questions