Pregunta

I am writing a sample chat application but I have problems with the security read rule. I only want that users can read messages after connecting to the chat application. For this I added a timestamp value to the message. Now I only want that if this timestamp >= the actual timestamp that the user can get this messages. But this doesn't work, because I can't access the $msgId (created by push) from parent. Here is my rules.json:

{
  "rules": {
    ".read": false,
    ".write": false,
    "chat": {
      ".write": false,
      ".read": false,

      "message": {
        ".write": false,
        ".read": "data.child($msgId).child('timestamp').val()  == now",

        "$msgId": {
          ".write": true,
          ".validate": "newData.hasChildren(['name','text','timestamp']) && newData.child('timestamp').val() == now"
        }

      },
  }
}
¿Fue útil?

Solución

You're making a mistake with "message" and "$msgId" as you probably don't want a "message" level but just directly the $msgId (if messages are directly the chat children). Hence, you should just combine these.

Then for the user creation date, it depends if you're saving your users in Firebase or somewhere else. If Firebase, then you could use something like root.child('users/' + auth.id + '/created_at') for your comparison. If somewhere else, use the auth token to pass the user signup date. In the meantime, Firebase provides server side timestamp for the comparison.

    "$msgId": {
      ".read": "data.child('timestamp').val() >= auth.created_date",
      ".write": true,
      ".validate": "newData.hasChildren(['name','text','timestamp']) && newData.child('timestamp').val() == now"
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top