子集合Firestore规则中的写入问题

时间:2019-03-26 15:58:47

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

我有一个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。

1 个答案:

答案 0 :(得分:2)

我从您的问题中得到的是,您希望将read, write的{​​{1}}授予具有/teachers/{teacher}/classes/{class}角色的某些用户。

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

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

true

现在添加以下规则:

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

否则,您需要使用firebase userid作为文档ID创建一个不同的集合,如果用户是校长,则添加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; } } } 字段,如下所示:

isHM

,然后添加以下规则:

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

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