Firebase Firestore Securitty Rule based on Attribute Value

こ雲淡風輕ζ 提交于 2020-01-06 06:54:34

问题


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:


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")...


来源:https://stackoverflow.com/questions/50526787/firebase-firestore-securitty-rule-based-on-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!