4

I have some articles.

Each article has a reference field to the profile document of the author who wrote that particular article.

Auth'd users (using Firebase's Auth) will be associated with these profiles.

How do I make these articles editable by the currently logged in user only if that user owns the article?

In Firestore's documentation, there is a recurring example:

service cloud.firestore {
  match /databases/{database}/documents {

    // Allows you to edit the current user document (like a user's profile).
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }

    // Allows you to read/write messages as long as you're logged in (doesn't matter who you're logged in as, so theoretically you could change other peoples' messages ).
    match /rooms/{roomId} {
      match /messages/{messageId} {
        allow read, write: if request.auth != null;
      }
    }

  }
}

Where is the example for how to structure and edit a document owned by a certain user?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
corysimmons
  • 7,296
  • 4
  • 57
  • 65

1 Answers1

8

Assuming you have a document with e.g. owner: <uid> stored in it, you can do:

service cloud.firestore {
  match /databases/{database}/documents {
    match /somecollection/{id} {
      allow write: if resource.data.owner == request.auth.uid;
    }
  }
}
Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
  • My article document doesn't have `owner: `, it has `owner: ` (i.e. `firestore.googleapis.com/project/xxxxxxxxx-eb000/database/(default)/documents/users/ajsidjasidjsaidjasidasj`). The reference _contains_ the uid. – corysimmons Nov 11 '17 at 05:25
  • 1
    Fwiw, I was trying exactly what you're proposing, but it doesn't seem to work with References. I suspect I need to do some `get()` stuff, but can't get the syntax just right... :( – corysimmons Nov 11 '17 at 05:35
  • 1
    When dealing with user information I'd recommend storing the uid as a string whenever you want to refer to an owner for this exact reason -- there's probably a way to do it otherwise but I'm not as sure how that would work. – Michael Bleigh Nov 12 '17 at 07:20
  • Thanks Michael. Apparently Firestore doesn't offer a way to validate using a Reference type (hopefully they'll add this and I've opened a Feature Request)... https://stackoverflow.com/questions/46568850/what-is-firestore-reference-data-type-good-for – corysimmons Nov 13 '17 at 20:07