【问题标题】:Rule for Firestore that enforce user to write a document with id equals to its own uidFirestore 的规则,强制用户编写 id 等于其自己的 uid 的文档
【发布时间】:2018-09-11 05:21:23
【问题描述】:

我想保证用户只能添加与其 auth.uid 具有相同 id 的文档。

例如,id 为 1X0T6xC6hhRN5H02zLCN6SQtwby2 的用户只能创建/更新文档 /salesmen/1X0T6xC6hhRN5H02zLCN6SQtwby2 。

在应用级别,通过以下命令完成(创建和更新)。

 this.db
    .collection("salesmen")
    .doc(user.uid)
    .set(data)
    .then(function() { //...

在 Firestore 级别,我正在尝试以下规则,但它不起作用(导致 写入文档时出错:错误:权限缺失或不足。)。

match /salesmen/{salesman} {
  allow read: if true;
  allow write: if request.auth != null && resource.id == request.auth.uid;
}

如何执行这条规则?

【问题讨论】:

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


    【解决方案1】:

    resource.id 只能用于引用 Firestore 中的现有文档。如果正在编写的文档尚不存在,则它不起作用。

    相反,您可以在匹配表达式中使用salesman 通配符来确定用户是否可以编写特定文档,即使它尚不存在:

    match /salesmen/{salesman} {
      allow read: if true;
      allow write: if request.auth != null && salesman == request.auth.uid;
    }
    

    看来您也可以使用request.resource.id 来引用可能尚未写入的文档的id:

    match /salesmen/{salesman} {
      allow read: if true;
      allow write: if request.auth != null && request.resource.id == request.auth.uid;
    }
    

    虽然目前我在reference documentation 中找不到明确讨论的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-10
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2019-06-15
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多