firestore 规则嵌套对象

firestore rules nested objects

我正在尝试为 Firestore 数据库设置规则。

我在为嵌套对象设置规则时遇到了一些问题。

数据库结构如下所示:

用户(用户对象的集合)

-----userDocument(文件名匹配auth-users uid)

----------------用户(用户的子集合)

------------------------userdocument(文件名与auth-users uid匹配)

注意:最后一个 userDocument 不包含任何引用。

他在主用户集合中有自己的文档。

我希望每个用户都可以 read/write 访问用户集合中的每个用户,这些用户在其用户子集合中具有匹配的用户 ID。 此外,任何用户都应该能够在数据库上创建新用户,只要他们通过 firebase Auth 进行身份验证。

我尝试了以下解决方案,但没有用:

    service cloud.firestore {
  match /databases/{database}/documents {
  match /users/{userId}{
  allow read, write: if exists(/databases/$(database)/documents/users/userId/users/$(request.auth.uid)) || userId == request.auth.uid;
  }
}
}

我需要的是:

该用户在他的子集合中有 1 个用户,因此该用户应该可以访问 read/write 他自己的用户和 qb2pa1TWXHZr0NZUREealgWrOYb2。

我找到了一个有效的解决方案,我希望这对以后的人有所帮助。

一切都经过全面测试、评论和工作。

service cloud.firestore {

//This is the "root" of the database. From here we can match into our collections.
  match /databases/{database}/documents {

    //matching the collection "users", the wildcard "userId" is used for the user we will be working with.
    match /users/{userId} 
    {
    //Everyone is allowed to write, if they are logged in.
    allow write: if request.auth.uid != null;
    //A user is allowed to read, update and delete his own account.
    allow read, update, delete: if request.auth.uid == userId;
    //A user is allowed to read a user, if the user matching "userId" exists in the logged in users own subcollection of users.
    allow read: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/users/$(userId));

                 //Matching the subcollection "users", still in the user matching userId.
           match /{users=**}{
           //A user is allowed to read, write, update, delete in the subcollection on his own account.
                 allow read, write, update, delete: if request.auth.uid == userId;
           //A user is allowed to read, write, update, delete in the subcollection, 
           //if the user matching "userId" exists in the logged in users own subcollection of users.
           allow read, write, update, delete: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/users/$(userId));
                 }
    }

    //matching the collection "duties", the wildcard "dutyId" is used for the duty we will be working with.
    match /duties/{dutyId}{
    //Everyone is allowed to write, if they are logged in.
    allow read, write: if request.auth.uid != null;
    // A user is allowed to read, write and update if the string in the field "ownerId" in the duty matching "dutyId" == the users Uid.
    allow read, update: if resource.data.ownerId == request.auth.uid;
    //A user is allowed, if the user matching "ownerId" exists in the logged in users subcollection of users.
    allow read, update, delete: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/users/$(resource.data.ownerId));
    }
  }
}