0

What should be the firebase rules for comment on post which is similar to facebook.

There are two things: first, only authenticated user can comment. Second, only the user who has commented can delete the comment. The user who has commented his id is saved in username. enter image description here

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Did you try writing anything yet? If so, please update your question to show. If not, have a look at the [Firebase documentation on securing user data](https://firebase.google.com/docs/database/security/user-security) and my recent [answer on that topic](https://stackoverflow.com/questions/51392059/firebase-email-saying-my-realtime-database-has-insecure-rules/51393449#51393449). To protect against deletion, see [securing for deletion](https://stackoverflow.com/questions/33491568/firebase-security-rules-for-remove-method). – Frank van Puffelen Sep 09 '18 at 16:48

1 Answers1

0

I strongly suggest using Firebase Bolt for writing/compiling Firebase Database Security rules. Data structure can get big and complicated. Using Bolt language you'll be able to easily write complex access and structure rules that can be re-used for other db patterns.

Your rules would look something like this:

path /comment/{postUid}/{commentUid} is Comment {
   read() { true }
   write() { isAuthor(this) || isAuthor(prior(this)) }
}

type Comment {
   text : String,
   username : String
}

isAuthor(value) { auth != null && value.username == auth.uid }

Pay attention to isAuthor(prior(this)) call. This is the way to make sure only author can delete a comment. prior function returns data as it was saved before current event (create, update or delete).

After using firebase-bolt tool to compile rules to JSON format you'll get:

{
  "rules": {
    "comment": {
      "$postUid": {
        "$commentUid": {
          ".validate": "newData.hasChildren(['text', 'username'])",
          "text": {
            ".validate": "newData.isString()"
          },
          "username": {
            ".validate": "newData.isString()"
          },
          "$other": {
            ".validate": "false"
          },
          ".read": "true",
          ".write": "auth != null && newData.child('username').val() == auth.uid || auth != null && data.child('username').val() == auth.uid"
        }
      }
    }
  }
}
Mladen
  • 189
  • 1
  • 8