0

我尝试向我的 firestore 数据库添加一个简单的规则。但是当我这样做时,当前用户的数据就会消失。

如果我控制台记录当前用户,它会打印出当前用户 UID 和电子邮件等。我可以注销并登录。但没有数据显示。有没有人知道我需要做什么或应该从哪里开始,因为现在我感到迷茫,我不知道我应该开始看什么。顺便说一句,我使用 React native 和 Redux 来获取我的数据。

这是我尝试添加的规则

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

这就是我在 redux 操作中获取用户的方式:

//fetch UserInfo from firebase
export function fetchUser() {
  return dispatch => {
    firebase
      .firestore()
      .collection('users')
      .doc(auth().currentUser.uid)
      .get()
      .then(snapshot => {
        if (snapshot.exists) {
          dispatch({type: USER_STATE_CHANGE, currentUser: snapshot.data()});
        } else {
          console.log('does not exist');
        }
      });
  };
}
4

1 回答 1

0

根据您创建的 Firestore 安全规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

逐行分解规则:

  • service cloud.firestore— 定义服务,在本例中为 cloud.firestore。
  • match /databases/{database}/documents— 定义数据库;{database} 子句表示这些规则适用于项目中的所有 Firestore 数据库。
  • match /{document=**}— 创建一个新规则块以应用于其中包含的所有文档。
  • allow write: allow read, write: if request.auth != null;— 允许对经过身份验证的会话进行读写访问。

您正在使用的规则会将集合中的所有文档提供给任何经过身份验证的用户,该用户与您创建的功能不匹配,其中它只请求currentUser.

删除安全规则将使该功能正常工作,因为它不会对查询应用任何安全限制,因此您允许任何未经身份验证的用户访问集合、子集合和文档。

相反,您应该利用 Firestore 安全规则的递归通配符

由于我还没有看到您的 Firestore 数据结构,这里有一个示例规则,用户只能读取和写入自己的数据:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /user/{userId}/{document=**} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

这将匹配用户集合的任何子集合中的文档以及用户集合中的文档。

您可以使用Rules Playground来验证您编写的 Firebase 安全规则。您可能还需要检查修复不安全规则以获得最佳安全实践。

于 2022-01-05T06:40:22.153 回答