0
votes

I am trying to write security rules on my Firestore database to allow read of documents within a collection with status value as published. But, it does not allow read for any document for the collection once the rule is published.

I am following the permission settings as described on the official doc. https://firebase.google.com/docs/firestore/security/rules-conditions

But, it is not working as expected.

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

    match /articles/{articleId} {
        allow read: if resource.data.status == 'published';
    }
  }
}

I am using the following React + Redux code for querying the documents:

export const getArticles = (limit = 25) => {
  return (dispatch) => {
    dispatch({ type: ARTICLES });

    const db = firebase.firestore();
    const query = db.collection('articles')
                    .orderBy('createdAt', 'desc')
                    .limit(limit);

    query.get()
    .then((snapshot) => {
      const dataArray = [];
      snapshot.forEach(doc => {
        dataArray.push(mergeDocIdAndData(doc.id, doc.data()));
      });
      getArticlesSuccess(dispatch, dataArray)
        .then(() => dispatch(push('/articles')));
    })
    .catch(() => getArticlesFail(dispatch));
  };
}
1
What is the code you are using to read the documents?Renaud Tarnec
I am using React + Redux. The following gist contains the method for reading data. gist.github.com/ishouvik/62d0f43974522b29f1ae3c4346862d22Shouvik Mukherjee
@ShouvikMukherjee Can you please include the relevant code in your question? Currently the accepted answer and your question can seem completely unrelated.André Kool
@AndréKool good remark. Shouvik Mukherjee, I've added the code used for querying, from the gist linked above.Renaud Tarnec

1 Answers

2
votes

You have missed one specific point in the doc: your query fails "because it does not include the same constraints as your security rules" and "security rules are not filters". See https://firebase.google.com/docs/firestore/security/rules-query#queries_and_security_rules

In other words, your query should be like:

const query = db.collection('articles').where("status", "==", "published")...