Querying with two array with firestore security rules

梦想的初衷 提交于 2021-01-28 20:02:46

问题


I currently have two arrays in a single document, one representing product ids and the other representing user ids. In my query, I need to query both of the arrays for firestore security rules to work correctly, but to do that, I tried using array-contains and in in the same query, which is acceptable in the documentation, but when I go to query, I get "missing or insufficient permissions".

db.collection('Depots')
  .where("products", "array-contains", productId)
  .where("users", "in", "lk9asdn340fk3fvb")
  .get();

This is my security rule:

function uidAndProductInDocument() {
    return request.auth.uid in resource.data.users;
}

This is what the contents of the document looks like:

However, even this security rule fails and does not return anything, even though there are docs in the database that should be returned, as they match the parameters.

I'm not sure how to secure the product relationship, as that relation for the product-user is in another document, and I have tried another approach in my other question, which can be found here: Firestore security rules: get() use in hasAny() list method

Is there anything that I am missing or need to do for this query to work?

Thanks in advance.


回答1:


You should consider restructuring your data in order to support the query you need. Since Firestore can't perform two array-contains queries, one of your arrays should be converted to an object, where the keys are values of the array, and the field value is simply true. For example, you could take your users list and make it look like this for each user:

users: {
  xxxx: true
  yyyy: true
}

Now you can query like this:

db.collection('Depots')
  .where("products", "array-contains", productId)
  .where(`users.${uid}`, "==", true)
  .get();

And your rule can check like this:

return resource.data.users[request.auth.uid]


来源:https://stackoverflow.com/questions/60893331/querying-with-two-array-with-firestore-security-rules

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