【问题标题】:Firestore no permissions to execute operationFirestore 没有执行操作的权限
【发布时间】:2020-07-13 12:11:13
【问题描述】:

我正在尝试在 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;
    }
  }
}

我的 Firestore 结构是:

Collection 'codes' > Document 'BNhBibYZ0ThCNCH2gzPRufFsIk22' > nothing in here

我的要求是:

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

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

我做错了什么?

【问题讨论】:

  • 查询时this.state.userID的确切值是多少? (您确定要使用onSnapshot() 而不是get()?)
  • 鉴于您的代码结构,我相当确定失败的是 onSnapshot,这意味着从 Firestore 的角度来看,您没有经过身份验证。您能否再次检查 firebase.auth().currentUser 是否为非空且 currentUser.uidthis.state.userID 匹配?
  • @DougStevenson 我可以确认 this.state.userID 是BNhBibYZ0ThCNCH2gzPRufFsIk22,但以防万一我也尝试对其进行硬编码。问题仍然存在。我用get() 替换了onSnapshot(),但它仍然是一样的。 @MichaelBleigh 在 set 函数之前,我已经打印出 auth().currentUser.uid 并且它与文档的名称相匹配,即 BNhBibYZ0ThCNCH2gzPRufFsIk22。我尝试只保留 .set 函数,但仍然存在权限问题。

标签: javascript firebase google-cloud-firestore firebase-security


【解决方案1】:

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

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

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

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

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;
    }
  }
}   

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

【讨论】:

  • 有趣的是,这部分帮助了我。在match /databases/{database} 之后,我错过了/documents。之后,一切都按预期进行。
  • 太棒了。我很高兴能帮上忙
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2016-09-16
  • 2021-09-25
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
相关资源
最近更新 更多