【问题标题】:How to get documents which is readable by user on Firestore Cloud depends on rules如何在 Firestore Cloud 上获取用户可读的文档取决于规则
【发布时间】:2018-09-01 01:00:25
【问题描述】:

我的 Firestore 云数据库有一条基本规则。我想给用户所在的用户咖啡馆,但我总是收到错误“缺少权限或权限不足。”。我错过了什么?

service cloud.firestore {
  match /databases/{db}/documents {    
    match /cafes{
        allow read: if request.auth.uid != null;

      match /{cafe}{
        allow read: if get(/databases/$(db)/documents/cafes/$(cafe)/participants/$(request.auth.uid)) != null;
            }
    }
  }
}

这是我用来访问文档的代码

export class MyApp {
  private rootPage:any;
  // rootPage:any = HomePage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, afAuth: AngularFireAuth, afs: AngularFirestore) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();

      afAuth.auth.onIdTokenChanged(user=>{
        if(user){
          console.log(user.uid)
          afs.collection('cafes').valueChanges().subscribe(console.log)
        } else {
          console.log('logged out')
        }
      })
    });
  }
}

【问题讨论】:

  • 您还应该包含您用来尝试阅读的代码(并给出错误)。

标签: firebase firebase-realtime-database firebase-authentication google-cloud-firestore


【解决方案1】:

docs on security rules 中的关键句子之一是

来自 Cloud Firestore 移动/网络客户端的每个数据库请求 阅读或 写入任何数据。

这应该可以回答您的问题:您不能通过文档对特定用户的可见性来查询文档,因为这需要 Firestore 读取和评估每个文档。

如果您阅读此规则

match /{cafe}{
    allow read: if get(/databases/$(db)/documents/cafes/$(cafe)/participants/$(request.auth.uid)) != null;
}

作为“如果参与者列表中包含他的用户 ID,则允许每个用户查看咖啡馆文档”,很明显 Firestore 需要阅读该文档来回答问题。

您可以尝试允许阅读所有咖啡馆文档,然后查询那些“用户所在的”,暗示用户也可以阅读其他咖啡馆。

您应该查看this official guide,了解有关对 Firestore 文档进行基于角色的访问的概念。

更新

我想更准确地说明“您不能通过文档对特定用户的可见性来查询文档,因为这需要 Firestore 读取和评估每个文档。”

您不能查询所有文档并期望获得对请求用户可见的文档(就像您在 afs.collection('cafes') 中所做的那样,即安全规则不是过滤器。

您可以做的是限定(添加 where 子句)您的查询以仅包含用户可见的文档。 Firestore 会将符合条件的查询与您的安全规则进行匹配,如果两者都匹配,则获取所需的结果。

【讨论】:

  • @HalilTevfik 我详细说明了“不能”这句话,但您可能已经从链接的文档中获取了该信息。
猜你喜欢
  • 2020-01-22
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2020-06-09
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多