Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict writes to a document owned by a user in Firestore?

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?

like image 567
corysimmons Avatar asked Mar 08 '23 15:03

corysimmons


1 Answers

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;
    }
  }
}
like image 175
Michael Bleigh Avatar answered May 05 '23 21:05

Michael Bleigh