代码之家  ›  专栏  ›  技术社区  ›  Val

Firestore安全规则总是第一次评估失败,第二次评估成功

  •  0
  • Val  · 技术社区  · 3 年前

    我有一个使用Firestore Web SDK(模块化)的React JS应用程序。安全规则(见下文)总是在第一次评估中失败,在第二次评估中成功。

    这两个评估在调试器中按顺序显示,几乎同时发生。但是DB操作只从代码中调用一次。这适用于数据库中的大多数集合。

    Firebase规则:

    rules_version = '2';
    
    service cloud.firestore {
        match /databases/{database}/documents {
    
            ...
    
            function isOwner(userId) {
                return request.auth != null && request.auth.uid == userId
            }
    
            function docData() {
                return resource.data;
            }
    
            function newDocData() {
                return request.resource.data
            }
    
            // Settings
            match /settings/{settingsId} {
                allow read, write: if isOwner(newDocData().userId) || isOwner(docData().userId);
            }
        }
    }
    
    

    写入的代码 settings 收藏:

    export async function updateSettings(userId?: string, updatedSettings?: Settings) {
        if (!updatedSettings || !userId) {
            throw new Error("Updated settings and user ID are required");
        }
        const settingsDocRef = doc(firestore, `${DB_PATH_SETTINGS}/${userId}`);
        await updateDoc(settingsDocRef, updatedSettings.toDbObject(true));
    }
    

    代码使用乐趣 toDbObject() ,它简单地将对象转换为:

    {
      "id": "v26SQ...X1IrT",
      "userId": "X6yMO...aGIZR",
      "notifications": [
        {
          "type": "campaign_changed_the_status",
          "isActive": true,
          "isEnabled": false
        },
        ...
      ],
      "emails": [
        {
          "email": "[email protected]",
          "isMain": true
        },
        ...
      ],
      "updatedAt": {
        "seconds": 1693555820,
        "nanoseconds": 353000000
      }
    }
    
    

    我打电话前后的数据差异 updateSettings() :

    enter image description here

    调试器的规则验证结果:

    enter image description here

    enter image description here

    如果能了解如何解决这个问题,或者至少如何调试它以找到原因,那就太好了。

    0 回复  |  直到 3 年前