Search code examples
reactjsreact-nativegoogle-cloud-firestorefirebase-security

Firebase rules checking an existing resource data but returning permission denied


These firebase rules return permission denied when an authenticated user tries to create a post with two fields, an authorId field that contains the user's id(uid) and an editStatus field that contains 'published' | 'draft'

   match /posts/{post} {
        allow read: if request.auth != null && resource.data.editStatus == 'published' 
            || request.auth.uid == resource.data.authorId;
        allow write: if  request.auth != null && request.auth.uid == resource.data.authorId;
      }

Can someone help me?


Solution

  • If you are creating a new document, you cannot check the resource.data.authorID as at that point in time, the resource does not exist. Instead, you will want to look at the request's value from request.resource.data.authorID.

    I also highly suggest breaking down your Security Rules into granular conditions to handle create vs update respectfully.

    Source: https://firebase.google.com/docs/firestore/security/rules-structure#granular_operations