Firestore 安全规则:get() returns 与预期不同的结果

Firestore security rules: get() returns different result than the expected one

我有一个 usernames 的 firestore 集合,其中每个用户名都充当文档 ID。每个单独的文档只有两个字段 - uid(所有者的 uid)和 createdAt。就这样。我想写一条安全规则,我说“如果你拥有用户名,你只能删除它”。所以这是我的安全规则:

match /usernames/{username} {
      function userOwnsUsername() {
        let unused = debug("does user owns username?");
        let uid = get(/databases/$(database)/documents/usernames/$(username)).data.uid;
        return debug(request.auth.uid == uid);
      }    
      allow delete: if isUserAuthenticated() && userOwnsUsername();
    }
function isUserAuthenticated() {
      return request.auth.uid != null;
    }

当我删除规则 userOwnsUsername 时,操作成功执行。谁能告诉我我做错了什么?

尝试从 accessed/updated 文档中读取数据时,您不必使用 get()。尝试使用 resource.data 代替:

match /usernames/{username} {
  function userOwnsUsername() {
    return request.auth.uid == resource.data.uid;
  }    
  allow delete: if isUserAuthenticated() && userOwnsUsername();
}