title: Firebase security rules for real-time messenger mobile App
body: <p>I'm building a real-time messenger using Ionic/Angular and Firebase. I'm using Firebase Authentication to authenticate my users, and Firebase DB to store the messages and message threads. </p>
  
  <p>My problem what security rules should I use in order for message threads to be private and viable and writable only to the 2 persons engaged in a given message thread.</p>
  
  <p>My DB structure looks like this now:</p>
  
  <pre><code>-chats
    --Message_thread_ID
      ---Unique_ID_generated_message by Firebase
         ----Message
         ----Sender ID
         ----Receiver ID
      ---Unique_ID_generated_message by Firebase
         ----Message
         ----Sender ID
         ----Receiver ID
    --Message_thread_ID
      ---Unique_ID_generated_message by Firebase
         ----Message
         ----Sender ID
         ----Receiver ID
  </code></pre>
  
  <p>My current firebase security rules are:</p>
  
  <pre><code>{
    "rules": {
      ".read": "auth != null",
      ".write": false,
      "$messageThreadID": {
          ".write": "auth != null &amp;&amp; !data.exists()",
          ".read": "auth != null"
      }
    }
  }
  </code></pre>
  
  <p>This works fine, but this way any authenticated user will be able to read all messages between any user. Which is no what I want. I want to keep message threads private to only the two users in any given thread.</p>
  
  <p>How should I restructure my DB for the best optimal solution?</p>
  
  <p>PS: I have ways to do it using backend, or making two copies for each of the two users of their respective threads, but these solutions look really subprime. </p>