【问题标题】:Firestore Rule That Checks Single Document Not Authenticating?检查单个文档未验证的 Firestore 规则?
【发布时间】:2020-05-16 01:33:17
【问题描述】:

我认为 Firebase 规则可能是一个简单的问题,但我似乎无法让它发挥作用。我有一个文档“公司”,里面有多个子集合。我想设置一个规则来检查“公司”文档中数组中的管理员(每个数组项都是 firebase userId 的字符串),并允许他们读取/写入该文档的所有子集合。

这是单个公司文档中的数据结构:

company1 {
  admins: ["userid1", "userid2", "userid3"],
}

这是我的 Firebase 规则:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /companies/{company}/{document=**} {
      allow read, write: if request.auth.uid in get(/databases/$(database)/documents/companies/$(company)).data.admins 
    }
  }
}

下面是一个在应该不工作的时候却不工作的查询示例:

let ref = db.collection("companies");

    //get current users company
    ref
      .where("admins", "array-contains", firebase.auth().currentUser.uid)
      .get()
      .then((snapshot) => {
        snapshot.forEach((doc) => {
          this.company = doc.data();
          this.company.id = doc.id;
      });
    });

我希望我的问题有意义:)

【问题讨论】:

  • 请编辑问题以显示不起作用的查询以及数据库中的相关数据。我们应该能够比较查询和规则,看看它们是否符合您的预期。
  • 嘿,Doug,我添加了更多信息,希望对上下文有所帮助!

标签: javascript firebase google-cloud-firestore firebase-security


【解决方案1】:

我找到了答案,希望对可能遇到此问题的人有所帮助。

我最终调整了数据结构,将公司文档 ID 作为字段包含在用户文档中。然后,我创建了这些规则以允许用户基于 firebase 身份验证读取/写入他们自己的用户文档,以及基于用户文档中的字段读取/写入他们的公司:

service cloud.firestore {
  match /databases/{database}/documents {

    // Allow users to create and edit the document for themselves in the users collection
    match /users/{user} {
      allow read, write: if request.auth.uid == user;
    }

    // Allow users to create a company for themselves upon signup
    match /companies/{company} {
      allow create: if request.auth.uid != null
    }

    match /companies/{company}/{document=**} {
      // Allow users to read/write data on thier own companies
      allow read, write: if company in get(/databases/$(database)/documents/users/$(request.auth.uid)).data.companies
    }
  }
}

【讨论】:

    猜你喜欢
    • 2020-07-04
    • 2021-05-30
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2018-09-29
    相关资源
    最近更新 更多