【问题标题】:Firebase rules/secure in collectionGroup use if state如果状态,则在 collectionGroup 中使用 Firebase 规则/安全
【发布时间】:2021-11-03 20:50:27
【问题描述】:

我对 firebase 规则有疑问。

此时我尝试设置新规则以提高数据库的安全性。

我的问题是在我的颤振代码中我使用了一个 collectionGroup 而且我不知道如何指定规则。

在 firebase 规则中,我创建了以下代码:

  • doc -> product_id(包含随机数和user_id)
  • 路径 -> product_details 的路径
//check product details
match /{path=**}/product_details/{doc}{
      
//check the user own the product -> is it -> he has all rules
allow read : if(doc.split('_')[2] == request.auth.uid);
      
//check the user own the product -> is not -> only can only read
allow write : if(doc.split('_')[2] != request.auth.uid);
      
//coming soon -> admin rules -> write/delete/read/update
}

为了检查用户是否在他自己的产品中,我拆分了 product_id。 product_id 还包含 user_id。

我的计划是用户只能读取、写入、更新和删除自己的产品。

其他用户的产品只能读取。

这只是一个例子。

如果我在上面的代码中设置“允许读取”状态,我的应用就可以正常工作。

但我正在更改状态(例如,使用 if 状态)我的应用出现错误。

在 firebase 调试中,我的代码运行良好。

在颤振中,collectionGroup 看起来像这样的代码:

//collection group all collection with 'product_images'
    Query<Map<String, dynamic>>  collectionGroupImage = FirebaseFirestore.instance.collectionGroup('product_images');

//get data from collection group
var query_product_images = await collectionGroupImage.get();

我在应用程序中遇到的错误类似于以下代码:

我的数据库: 路径:/user/user_id/data/product_data/product_details/product_id/paramter(price,discription...)

我将一个用户的所有产品添加到用户中(参见上面的路径)

我的问题是,如果我想在我的应用中显示所有产品 我需要所有产品的 ID。 为了解决这个问题,我在我的“product_details”上创建了一个 collectionGroup。 现在我可以在我的产品中获得所有价值。 直到现在它的工作。

如果有任何问题,请随时问我。

任何人都知道如何在代码中设置 if 状态。 多谢

【问题讨论】:

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


    【解决方案1】:

    由于您希望用户能够查看所有 product_details 数据:请将此规则用于您的集合组

    match /{path=**}/product_details/{docId}{
      allow read: if true;
      // allow read: if (request.auth != null); use this line if you want to 
      // allow only logged in users.
    }
    

    然后,为了防止一个用户修改另一个用户的数据,使用这样的东西

    function isLoggedIn() {
      return request.auth != null;
    }
    function isOwner(detailsId) {
      return isLoggedIn() && detailsId.split('_')[2] == request.auth.uid;
    }
    match /product_details/{detailsId} {
      allow update, delete, create: if isOwner(detailsId);
    }
    

    【讨论】:

    • 你好彼得,谢谢你的回答。我需要 collectionGroup 来显示所有用户的所有产品。在你的例子中(我认为)我只选择我的产品。 Tahts 不是我想做的事。在我的问题中,我更新了我的数据库以更好地解释我的问题。
    • 如果您希望您的 collectionGroup 显示来自所有用户的产品,那么您的 firestore 规则应该是:match /{path=**}/product_details/{docId}{allow read: if true;} 或如果您只想登录用户读取所有产品数据,您的 Firestore 规则应为:match /{path=**}/product_details/{docId}{allow read: if (request.auth != null);}跨度>
    • 你好彼得,谢谢你的回答。这是有效的。但是如何检查用户是否拥有该产品?为此,我需要用户 ID。但我不知道如何从 'path=**' 得到它?这就是我拆分产品编号的原因。产品编号包含 id_randomNumber_UserID。但如果我分裂它不起作用。在调试模式下firebase它的工作原理?你有想法吗?多谢
    • 它工作正常。许多 Thx (:. 你拯救了我的一天
    • 很高兴我能帮上忙。
    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多