title: Firebase Firestore - Limit the number of product-documents users can create
body: <p>I have an Angular web-app with Firebase as the serverless backend technology. The current purpose of the web-app is to let registered users create documents for offered products. While business users can create unlimited product-docs, free users should only be able to create one product-doc.</p>
  <p><strong>Collections:</strong></p>
  <ul>
  <li>users - <code>{id: string, isBusiness: boolean, name: string, email: string, productIds: string[]}</code></li>
  <li>products - <code>{id: string, title: string, description: string, userId: string}</code></li>
  </ul>
  <p>Whenever a user creates a new product-doc with</p>
  <pre class="lang-js prettyprint-override"><code>  public createProduct(id: string, product: Product) {
      return this.afStore.collection('products').doc(id).set(product, { merge: true });
    }
  </code></pre>
  <p>I run a cloud function with the trigger <code>onCreate</code> to add the <code>id</code> of the created product-doc to the <code>productIds</code> field of the according user-doc. This allows me to check frontend-side <code>if(!user.isBusiness &amp;&amp; productIds.length &gt; 1)</code> to limit the creation of multiple product-docs for free user accounts.</p>
  <p>However, I recently did a pen-test and the testers accidentality found out that if you open the website on multiple browser tabs and simultaneously run the <code>createProduct()</code> function on each tab at the same time, all of them will execute allowing a non business user to have several product-docs.</p>
  <p>Has anybody dealt with a similar situation? I don´t know if there is a way to avoid this with Firestore Security Rules, or if there is something to wait until active transactions are finished.</p>