【问题标题】:Firebase database rules, only allow delete if the document property equals the authenticated user idFirebase 数据库规则,仅当文档属性等于经过身份验证的用户 ID 时才允许删除
【发布时间】:2019-09-14 10:24:04
【问题描述】:

我在我的 firebase 数据库中添加安全规则时遇到问题。如果经过身份验证的用户等于投票文档上的 uid 属性,我只想允许删除投票。除了我在 match /votes/{voteId} 上创建的删除规则之外,一切正常。

我尝试使用 resource.data.uid 执行此操作,但模拟器抱怨并且我收到错误“运行模拟时出错 - 错误:simulator.rules Null 值错误”

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

    match /polls/{pollId} {
      allow read;
      allow delete: if getUserData().roles.keys().hasAny(['admin']);
      allow create: if isSignedIn();
    }

    match /users/{userId} {
        allow read, write: if isOwner(userId);
    }

    match /votes/{voteId} {
        allow read;
      allow create: if isSignedIn();
      allow delete: if request.auth.uid == resource.data.uid;
    }
  }

  /// Functions ///
  function isSignedIn() {
    return request.auth != null
  }

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

}

更新

我也尝试使用 /{document=**} 通配符,它​​给了我相同的 Null 值错误

match /votes/{document=**} {
        allow read;
      allow create: if isSignedIn();
      allow delete: if request.auth.uid == resource.data.uid;
    }

我也尝试使用 get() 函数,但收到错误“未找到函数错误:名称:[get]”

match /votes/{voteId} {
  allow read;
  allow create: if isSignedIn();
  allow delete: if get(/databases/$(database)/documents/votes/$(voteId)).data.uid == request.auth.uid
}

【问题讨论】:

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


    【解决方案1】:

    您是否创建了一个包含名为uid 的字段的文档?像这样。

    firebase.firestore().collections("votes").add({uid: firebase.auth().currentUser.uid});

    resource 是一个 Firestore 文档。

    resource.data是文档数据的映射。

    firebase 控制台上的模拟器正在使用您项目中存在的真实 firestore 数据。

    而且我认为将规则更改为以下规则更好。

    ...
        match /votes/{voteId} {
            allow read;
          allow create: if isSignedIn() && request.auth.uid == request.resource.data.uid;
          allow delete: if isSignedIn() && request.auth.uid == resource.data.uid;
        }
    ...
    
      function isSignedIn() {
        return request.auth.uid != null
      }
    ...
    

    见:

    【讨论】:

    • 你怎么知道什么时候使用 request.resource.data.uid 和 resource.data.uid?
    • 文档是here
    猜你喜欢
    • 2020-03-06
    • 2022-01-25
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2020-09-24
    • 2018-10-10
    相关资源
    最近更新 更多