【问题标题】:Problem with write in subcollections Firestore Rules写入子集合 Firestore 规则的问题
【发布时间】:2019-08-17 02:07:35
【问题描述】:

我有一个 Firestore 数据库,其结构如下:

collection (teachers): {
  doc (id): {
    name: name
    lastName: lastName
    collection (classes): {
      doc (id): {
        name: math
      }
    }
  }
}

我想要实现的是校长能够获得teacher 的名字并为同一位老师添加/创建一些课程。问题在于添加 Firestore 规则。我已经尝试了这三种规则的可能性,但没有一个按预期工作。我能读,但不能写。

1

service cloud.firestore {
  match /databases/{database}/documents {
    match /teachers/{teacher} {
        allow get if true;
        allow create if true;
    }
  }
}

2

service cloud.firestore {
  match /databases/{database}/documents {
    match /teachers/{teacher} {
        allow get if true;
    }
    match /teachers/{teacher}/classes/{class} {
    allow create if true;
  }
}

3

service cloud.firestore {
  match /databases/{database}/documents {
    match /teachers/{teacher} {
        allow get if true;
      match /classes/{class} {
        allow create if true;
      }
    }
}

顺便说一下,我正在使用 angularfirestore2。

【问题讨论】:

  • 您如何识别用户是“校长”?所有用户都是“校长”吗? “非校长”用户能做什么?目前还不是 100% 清楚您要实施哪些访问权限。
  • 我可以识别校长,我不能做的是设置权限,一旦设置了老师,根据我提到的路径写入更深的文档。感谢您的回复。

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


【解决方案1】:

我从您的问题中得到的是,您想将read, write for /teachers/{teacher}/classes/{class} 提供给一些具有headmaster 角色的用户。

为此,首先您需要检查哪些用户是headmasters

如果您的教师文档 ID 与在 Firebase 身份验证中创建的用户 ID 相同,您可以在教师文档中添加一个名为 isHM 的数据字段,并将其设置为 true,如果用户是校长:

collection (teachers): {
  doc (id): {
    name: name
    lastName: lastName
    isHM: true
    collection (classes): {
      doc (id): {
        name: math
      }
    }
  }
}

现在添加以下规则:

service cloud.firestore {
   match /databases/{database}/documents {
     match /teachers/{teacher}/classes/{class} {

        function isHeadMaster() {
          return get(/databases/$(database)/documents/teachers/$(request.auth.uid)).data.isHM;
        }

        // HM can read, write classes
        allow read, write: if isHeadMaster == true;

     }
   }
}

否则您需要创建一个不同的集合,使用 firebase userid 作为 doc id,如果用户是校长,则添加 isHM 字段,如下所示:

collection (headmasters): {
  doc (uid): {
    ----
    isHM: true
    ----
  }
}

然后添加以下规则:

service cloud.firestore {
   match /databases/{database}/documents {
     match /teachers/{teacher}/classes/{class} {

        function isHeadMaster() {
          return get(/databases/$(database)/documents/headmasters/$(request.auth.uid)).data.isHM;
        }

        // HM can read, write classes
        allow read, write: if isHeadMaster == true;

     }
   }
}

要查找更多基于角色的访问规则,请查看此https://firebase.google.com/docs/firestore/solutions/role-based-access

【讨论】:

    猜你喜欢
    • 2018-11-27
    • 1970-01-01
    • 2018-07-14
    • 2019-12-23
    • 2018-07-02
    • 1970-01-01
    • 2020-12-18
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多