firebase 匹配自定义声明与firestore文档ID

wmvff8tz  于 2023-08-07  发布在  其他
关注(0)|答案(2)|浏览(108)

我的数据大致如下:

/databases/schools/{schoolId}/faculty
                             /students
                             /etc

字符串
我有一群人在他们的帐户上有一个自定义的“schoolId”。我只希望他们能够访问他们所属学校的教师、学生等。尝试了此规则的多次迭代,最新的一次是

service cloud.firestore {
  match /databases/schools/{document} {
    match /{doc=**} {
      allow read, write: if user.token.schoolId == document;
    }
  }
}


其他迭代包括:

service cloud.firestore {
  match /databases/schools/{document} {
    allow read, write: if user.token.schoolId == document;
  }
}


和/或

service cloud.firestore {
  match /databases/schools {
    match /{document=**} {
      allow read, write: if user.token.schoolId == document;
    }
  }
}


或者是

service cloud.firestore {
  match /databases/{database}/documents {
    match /{$document} {
      allow read, write: if resource.id == user.token.schoolId;
    }
  }
}


这感觉应该是一个相当简单的事情,但我不能弄清楚(我在我的第12次迭代)
我想我明白最后一个是不工作的,因为如果我试图得到/databases/schools/school 1/faculty/abc123,那么resource.id实际上是指abc123而不是school 1。
当我解码令牌时,示例用户看起来像这样:

uid: "gobblygook"
displayName: null
photoURL: null
email: "test-email@yopmail.com"
emailVerified: true
phoneNumber: null
isAnonymous: false
apiKey: "{apikey}"
appName: "[DEFAULT]"
authDomain: "{mydomain}.firebaseapp.com"
lastLoginAt: "1538972960000"
createdAt: "1538868952000"
schoolId: "school1"

mzmfm0qo

mzmfm0qo1#

以下内容应该有效:

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

     match schools/{schoolId} {
       allow read: if request.auth.token.schoolId == resource.data.schoolId;
       allow write: if request.auth.token.schoolId == request.resource.data.schoolId;
     }        

  }
}

字符串
请注意:
1.我猜对于/databases/schools/{schoolId}/,你的意思是根集合是schools而不是databases
1.您必须使用request.auth.token.schoolId才能通过用户的ID令牌检索Custom Claim,参见https://firebase.google.com/docs/auth/admin/custom-claims
1.在写规则中使用request.resource.data.schoolId;,而不是resource.data.schoolId;

q43xntqr

q43xntqr2#

今天早上终于弄明白了,感谢雷诺为我指明了正确的方向!也感谢这个如此的答案Recursive wildcards in Firestore security rules not working as expected

service cloud.firestore {
  match /databases/{database}/documents {
    match /schools/{schoolId} {
      allow read, write: if request.auth.token.schoolId == schoolId
    }

    match /schools/{schoolId}/{document=**} {
      allow read, write: if request.auth.token.schoolId == schoolId
    }
  }
}

字符串
似乎正在做我想让它做的事情(我可以切换==等于!=我的用户不再具有访问权限)

相关问题