Search code examples
firebase-security

How to allow firebase user to only access documents that they created


This, to me, is the most basic authentication scheme for user-generated content, given a collection called "posts":

  1. Allow any authenticated user to insert into "posts" collection
  2. Allow the user who inserted the document into collection "posts", to read, update, and destroy the document, and deny all others
  3. Allow the user to list all documents in collection "posts" if they are the one who created the documents originally

All examples I've found so far seem to rely on the document ID being the same as the user's id, which would only work for user's "profile" data (again, all the examples seem to be for this single limited scenario).

It doesn't seem that there is any sort of metadata for who the authenticated user was when a document was created, so it seems i must store the ID on the doc myself, but I haven't been able to get past this point and create a working example. Also, this opens up the opportunity for user's to create documents as other users, since the user ID is set by the client.

I feel like I am missing something fundamental here since this has to be the most basic scenario but have not yet found any concise examples for doing this.


Solution

  • This answer is from this github gist. Basically, in the document collection posts there is a field called uid and it checks if it matches the users uid.

    // Checks auth uid equals database node uid
    // In other words, the User can only access their own data
    
    {
      "rules": {
        "posts": {
           "$uid": {
             ".read": "$uid === auth.uid",
             ".write": "$uid === auth.uid"
           }
         }
       }
    }
    

    -- Edit --

    DSL rules

    match /Posts/{document=**}{
        allow read : if uid == request.auth.uid;
        allow write: if uid == request.auth.uid;
    }