我正在为用于Firebase的Cloud Firestore编写规则,并且我想使用用户的auth ID限制对数据库的访问,但是这些规则的行为并不符合我的期望。

所以,我的数据库结构是这样的:

/ users / {userId} / groups / {groupId}

我只希望用户只能使用自己的userId访问文档。

为此,我编写了如下规则:

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

    match /users/{userId=**} {
        allow read: if userId == request.auth.uid;
    }

  }
}


但是,与此同时,我的用户无法从数据库中读取他们自己的“组”。

我正在使用javascript,以下是用于检索“组”的代码:

console.log("uid: ", uid)
db.collection("users/" + uid + "/groups")
  .onSnapshot(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
      console.log(doc.data())
    })
})


现在,由于Cloud Firestore没有像实时数据库这样的调试工具,因此我自己进行了一些调试。

我有一个uid为“ 5lS2NA21UgbabEw4AkyWyef9FH42”的测试用户,因此我更改了如下规则:

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

    match /users/{userId=**} {
        allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == request.auth.uid;
    }

  }
}


这样,我的测试用户就可以从他的文档中成功检索“组”数据(其他所有用户当然不能,但是)。

现在,我将规则更改为:

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

    match /users/{userId=**} {
        allow read: if "5lS2NA21UgbabEw4AkyWyef9FH42" == userId;
    }

  }
}


现在,我无法从数据库中获取任何数据。

有人可以告诉我我在做什么错吗?

最佳答案

我想我已经知道了。问题是这个{userId = **}

如果您有以下规则

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

    match /users/{userId=**} {
        allow read: if userId == request.auth.uid;
    }

  }
}


并尝试访问users / 5lS2NA21UgbabEw4AkyWyef9FH42 / groups,“ userId”变量的评估结果不是5lS2NA21UgbabEw4AkyWyef9FH42(我不知道会是什么,但我猜是“ 5lS2NA21UgbabEf4AkyWyef” /)。因此,如果要私有化文档,则必须像下面一样指定规则中的每个文档。

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

    match /users/{userId} {
        match /groups/{groupId} {
           allow read: if userId == request.auth.uid;
        }
        match /events/{eventId} {
           allow read: if userId == request.auth.uid;
        }
    }

  }
}

10-07 13:08
查看更多