Search code examples
firebasegoogle-cloud-firestorefirebase-authenticationrules

firestore how to check for the doc owner before write?


How do I check the document owner before allow for the user the create ? steps:

  1. the document is already created by the same owner.
  2. after that the same owner will try to create property and value inside the doc.

document.owner give me error when publishing.

//only allow create in moviesCommentID/{document} when document is owned by the user
match /moviesCommentID/{document=**} {
    allow create: if request.auth != null && document.owner == request.auth.uid;
}

any help is greatly appreciated.


Solution

  • 1- Creation

    You need to have a field in the Firestore Document you are changing that stores the owner uid

    allow create: if request.auth != null && resource.data.ownerUid == request.auth.uid;
    

    2- Update:

    Use the same as for "create" (owner is actually the person logged), but also add something to say they cant change the owner to another user

    allow update: if request.resource.data.ownerUid== resource.data.ownerUid;
    

    Note that request.resource variable contains the future state of the document