允许用户读取、写入自己的文档 Firestore

use*_*893 2 javascript firebase-security google-cloud-firestore

我正在尝试设置 firestore 安全性,以便用户可以读取和写入自己的文档,这是我用来将数据添加到数据库的代码

data() {
  return {
    order: {
      price: null,
      amount: null,
      comment: null,
      createdAt: new Date().toString().slice(0, 25),
      uid: fb.auth().currentUser.uid
    }
  }
}

sendBuy() {
  db.collection("orders").add(this.order);
}
Run Code Online (Sandbox Code Playgroud)

这是读取数据的代码

readData() {
  let uid = fb.auth().currentUser.uid;
  db.collection("orders")
    .where("uid", "==", uid)
    .get()
    .then(querySnapShot => {
      querySnapShot.forEach(doc => {
        console.log(doc.id, "=>", doc.data());
      });
    });
}
Run Code Online (Sandbox Code Playgroud)

我尝试过的 firestore 规则不起作用

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /orders/{uid} {
      allow read, write: if request.resource.data.uid == request.auth.uid;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

请问我怎样才能实现这个目标

Gra*_*ton 5

这些规则应该有效:

allow read: if resource.data.uid == request.auth.uid;
allow write: if request.resource.data.uid == request.auth.uid;
Run Code Online (Sandbox Code Playgroud)

要修复写入中的安全漏洞,您可以执行以下操作(保持读取相同):

allow create: if request.resource.data.uid == request.auth.uid
allow update, delete: if resource.data.uid == request.auth.uid && request.resource.data.uid == resource.data.uid
Run Code Online (Sandbox Code Playgroud)

这允许任何登录的人创建属于他们的订单。它仅允许用户更新与其 uid 匹配的订单,并且不允许用户更改 uid。