title: Firebase - Limit file access to specific users
body: <p>I'm trying to achieve the following behavior using Firebase:</p>
  
  <ul>
  <li>User logs in using Firebase Authentication</li>
  <li>User uploads a file to Firebase Storage</li>
  <li>User enters an email address of a different user. This user account may already exist. If not, the recipient gets an email prompting them to sign up.</li>
  <li>The uploaded file should now be available only to the user who uploaded it (read/write) and to the other user with the above email address (read only).</li>
  </ul>
  
  <p>This is what I've been trying so far:</p>
  
  <ul>
  <li>After using FirebaseAuth to sign up, I store the user's email address and <code>uid</code> in the Real-Time Database.</li>
  <li>After the user uploads a file and enters the recipient's email address, I check the Real-Time Database for that address. If it exists, I retrieve the recipient's <code>uid</code> and store it in the file's metadata.</li>
  <li>In my Firebase Storage security rules, I check if the <code>auth.uid</code> matches the <code>uid</code> stored in the file metadata.</li>
  </ul>
  
  <p>This should work well, but what do I do if the user account does not yet exist?</p>
  
  <ul>
  <li><p>I could create a new account after the user enters the recipient's email address. If I do that though, I have to specify a password. I could specify a random password and use the password reset email, but that isn't a good user experience, also because you can't fully customize the reset email.</p></li>
  <li><p>If I don't create the new account right away, how can I make sure that only the user with this email address can access the file? Storing the email address in the file's metadata doesn't work since it could change later.</p></li>
  </ul>
  
  <p>I have a feeling I'm thinking way too complicated here. Is there an easier way to achieve this, or am I overlooking something?</p>
  
  <p>EDIT: I've investigated a bit more and I think one way to do this would be by using a custom auth token, which is suggested by the Firebase Storage guide <a href="https://firebase.google.com/docs/storage/security/user-security#group_private" rel="nofollow">here</a>. That would require me to setup my own auth server though, which kind of defeats the purpose of using Firebase Authentication in the first place. Is there an easier way to achieve this?</p>