Firestore没有执行操作的权限

EDJ*_*EDJ 3 javascript firebase firebase-security google-cloud-firestore

我正在尝试在 Firestore 中设置规则,如果每个人都经过身份验证进入应用程序,则每个人都可以读取彼此的内容,但只有文档所有者才能创建、写入、更新或删除它们。

我在 Firestore 中设置了以下规则:

rules_version = '2';

service cloud.firestore {
  match /databases/{database} {
    match /codes/{userID} {
      allow create, write, update, delete: if request.auth.uid == userID;
      allow read: if request.auth.uid != null;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我的 Firestore 结构是:

Collection 'codes' > Document 'BNhBibYZ0ThCNCH2gzPRufFsIk22' > nothing in here
Run Code Online (Sandbox Code Playgroud)

我的要求是:

firestore()
  .collection('codes')
  .doc(this.state.userID)
  .onSnapshot((querySnapshot) => {
    if (!querySnapshot) {
      let testObj = {"hello": "world"} 
      firestore().collection('codes').doc(this.state.userID).set(testObj);
    }
  });
Run Code Online (Sandbox Code Playgroud)

我收到的输出是:Error: [firestore/permission-denied] The caller does not have permission to execute the specified operation.

我究竟做错了什么?

Ary*_*tey 5

您可以使用我创建的以下函数来执行此操作

function isUserAuthenticated() {
    return request.auth.uid != null; 
}

function belongsTo(userId) {
    return request.auth.uid == userId;
}

Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }

    match /codes/{userId} {
      allow read : if isUserAuthenticated();
      allow create : if belongsTo(userId);
      allow update: if belongsTo(userId);
      allow delete: if belongsTo(userId);
    }

    /* Functions */
    function isUserAuthenticated() {
      return request.auth.uid != null; 
    }

    function belongsTo(userId) {
      return request.auth.uid == userId;
    }
  }
}   
Run Code Online (Sandbox Code Playgroud)

如果它适合您,请接受作为答案。更多问题可在评论中解答。