Firestore规则不适用于userId

时间:2017-10-21 04:05:51

标签: firebase google-cloud-firestore

我有一个简单的集合用户,文档ID使用带名称字符串的uid enter image description here

我使用angularfire2连接到集合

this.users = afs.collection<User>('users').valueChanges();

我正在使用firebase身份验证。显示用户ID时,我得到与用户文档匹配的4NxoeUeB4OXverhHhiw86eKl0Sj1。

this.afAuth.authState.subscribe(auth => console.log(auth.uid));

我试图为集合添加规则。如果我使用下面的规则,我会收到错误或权限不足的错误。

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth.uid == userId;
    }
  }
}`

如果我将规则更改为request.auth!= null,则会显示数据。

`service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
        allow read, write: if request.auth != null;
    }
  }
}`

我做错了什么?我也尝试了一些不同的规则,例如。 resource.data.name != null。它也无法正常工作。

我正在测试规则。最终的结果我想要一个读者数组字段和编写器数组字段,所以我可以尝试request.auth.uid in resource.data.readers之类的东西来控制对文档的访问

1 个答案:

答案 0 :(得分:4)

您尝试获取/users/*,但只能访问/users/{yourid}

您应该只检索您有权访问的数据,因此即使您实际只有一个文档,也需要过滤查询。

// either by adding a field in your doc
afs.collection('users', ref => ref.where('id', '==', auth.uid))

// or by getting the document directly
afs.collection('users').doc(auth.uid)
  

对查询执行规则检查时,Cloud Firestore安全性   规则将检查以确保用户有权访问所有结果   在执行查询之前。如果查询可以返回用户的结果   无权访问,整个查询失败,Firestore返回   错误。

来源:https://cloud.google.com/firestore/docs/security/secure-data#shallow_queries