ErickXavier
ErickXavier

Reputation: 978

Cloud Firestore permissions

I have the following permissions configured in my Cloud Firestore, but I'm having some problems with the visualization of my items.

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{document=**} {
      allow read;
    }
    match /pages/{pageid} {

      // Returns true if the user is logged        
      function isSignedIn() {
        return request.auth != null;
      }

      // Returns true if the logged user is admin
      function isAdmin() {
        return isSignedIn()
            && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true;
      }

      // Returns true if the requested page has published marked as true (or should, at least :( )
      function isPublished() {
        return resource.data.published == true;
      }

      allow read: if isPublished() || isAdmin();
      allow write: if isAdmin();
    }
  }
}

I can't make the isPublished() to work properly. The content is not being shown as it should be. the isAdmin() works properly.

My data has the property published configured as boolean as expected and all of them but one is checked as true. Nothing is shown and this error appears in the browser:

core.js:14597 ERROR Error: Missing or insufficient permissions.

Does anyone have any idea how to fix this?

By the way, my code is based on the docs: https://firebase.google.com/docs/firestore/security/rules-query#evaluating_constraints_on_queries

Here is an example of the data I'm trying to read from: enter image description here

And the constructor of my Angular Service getting a list of the pages:

constructor(
  public afs: AngularFirestore) {   

    this.pagesCollection = this.afs.collection('pages', ref => ref.orderBy('order', 'asc'));

    this.pages = this.pagesCollection.snapshotChanges().pipe(
      map(changes => {
        return changes.map(a => {
          const data = a.payload.doc.data() as Page;
          data.id = a.payload.doc.id;
          return data;
        })
      })
    );
}

getPages(){
  return this.pages;   
}

Upvotes: 1

Views: 428

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599946

You're trying to read all documents, which your rules do not allow. Keep in mind that security rules don't filter documents. They merely ensure that the read operation matches the rules, which in your case it doesn't.

This means you'll need to replicate the logic from your rule in your query, by only requesting published documents:

ref.where('published', '==', true).orderBy('order', 'asc')

For more on this, see:

Upvotes: 3

Related Questions