gpt4 book ai didi

google-cloud-firestore - 仅当Firebase Firestore中不存在文档时才创建它

转载 作者:行者123 更新时间:2023-12-04 07:32:41 24 4
gpt4 key购买 nike

我要实现的目标非常简单。仅在数据库中不存在用户条目时,才需要创建该用户条目。
应用流程:

  • 创建具有Firebase身份验证的用户(获取UID)
  • 使用UID作为键
  • 在数据库中创建用户文档

    客户端代码(创建操作):
    this.db.doc('users/' + uid).set({username: Santa})
    消防站规则:
    service cloud.firestore {
    match /databases/{database}/documents {
    match /users/{uid} {
    allow create: if
    request.auth != null &&
    request.auth.uid == uid &&
    !exists(/databases/$(database)/documents/users/$(uid));
    allow update: if request.auth != null && request.auth.uid == uid;
    }
    }
    }
    附加信息:
    您可能已经知道该代码无法正常工作。每次我运行客户端代码时,当前用户都会被新文档完全替换。但是,如果我从规则中删除以下行,那么一切都会按预期进行:
    allow update: if request.auth != null && request.auth.uid == uid;
    但是现在出现了问题,如何保护用户文档中的数据免遭未经授权的修改?有什么建议吗?

    最佳答案

    如果您只想在尚不存在的情况下才允许创建它,则只需使用已有的allow create规则即可。因为您也有allow update规则,所以也允许更新现有数据。

    以下规则应足够:

    service cloud.firestore {
    match /databases/{database}/documents {
    match /users/{uid} {
    allow create: if request.auth != null && request.auth.uid == uid;
    }
    }
    }

    您不需要 exists()调用,因为 allow create仅在数据不存在时才适用。

    现在,您的问题是:您应该明确说明您的意思。现在,只有经过身份验证的用户才能修改自己的记录。如果您不想允许写入任意数据,请检查它。

    这里有些例子:
    https://firebase.google.com/docs/firestore/security/rules-conditions#authentication

    关于google-cloud-firestore - 仅当Firebase Firestore中不存在文档时才创建它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46888701/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com