為 Cloud Firestore 安全性規則寫入條件

本指南以建構安全性規則指南為基礎,說明如何在 Cloud Firestore 安全性規則中新增條件。如果您還不熟悉 Cloud Firestore 安全性規則的基本概念,請參閱入門指南

條件為 Cloud Firestore 安全性規則的主要構成要素。條件是一種布林值運算式,可判定是否應允許或拒絕特定作業。使用安全性規則編寫條件,檢查使用者驗證、驗證傳入資料,甚至是存取資料庫的其他部分。

驗證機制

最常見的安全性規則模式之一,就是根據使用者的驗證狀態來控管存取權。舉例來說,應用程式可能想只允許已登入的使用者寫入資料:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow the user to access documents in the "cities" collection
    // only if they are authenticated.
    match /cities/{city} {
      allow read, write: if request.auth != null;
    }
  }
}

另一個常見的模式是確保使用者只能讀取及寫入自己的資料:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow read, update, delete: if request.auth != null && request.auth.uid == userId;
      allow create: if request.auth != null;
    }
  }
}

如果您的應用程式使用 Firebase 驗證或 Google Cloud Identity Platformrequest.auth 變數會包含用戶端要求資料的驗證資訊。如要進一步瞭解 request.auth,請參閱參考說明文件

資料驗證

許多應用程式會將存取權控管資訊儲存為資料庫中文件的欄位。Cloud Firestore Security Rules 可根據文件資料,動態允許或拒絕存取:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow the user to read data if the document has the 'visibility'
    // field set to 'public'
    match /cities/{city} {
      allow read: if resource.data.visibility == 'public';
    }
  }
}

resource 變數參照要求的文件,而 resource.data 是文件中所有欄位和值的對應。如要進一步瞭解 resource 變數,請參閱參考說明文件

寫入資料時,您可能會想比較傳入的資料與現有資料。在這種情況下,如果您的規則集允許待處理的寫入作業,request.resource 變數就會包含文件的未來狀態。針對只會修改文件欄位子集的 update 作業,request.resource 變數會在作業後包含待處理的文件狀態。您可以檢查 request.resource 中的欄位值,以免發生不必要或不一致的資料更新:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure all cities have a positive population and
    // the name is not changed
    match /cities/{city} {
      allow update: if request.resource.data.population > 0
                    && request.resource.data.name == resource.data.name;
    }
  }
}

存取其他文件

透過使用 get()exists() 函式,安全性規則可以評估傳入的要求,並與資料庫中的其他文件進行比較。get()exists() 函式都會預期完整的文件路徑。使用變數建構 get()exists() 的路徑時,您必須使用 $(variable) 語法明確逸出變數。

在以下範例中,比對陳述式 match /databases/{database}/documents 會擷取 database 變數,並用於建立路徑:

service cloud.firestore {
  match /databases/{database}/documents {
    match /cities/{city} {
      // Make sure a 'users' document exists for the requesting user before
      // allowing any writes to the 'cities' collection
      allow create: if request.auth != null && exists(/databases/$(database)/documents/users/$(request.auth.uid))

      // Allow the user to delete cities if their user document has the
      // 'admin' field set to 'true'
      allow delete: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true
    }
  }
}

對於寫入作業,您可以在交易或批次寫入作業完成之後 (交易或批次修訂之前),使用 getAfter() 函式存取文件的狀態。和 get() 一樣,getAfter() 函式會使用完整指定的文件路徑。您可以使用 getAfter() 定義必須一起進行為交易或批次進行的寫入作業組合。

存取通話限制

每項規則集的評估作業有文件存取呼叫限制:

  • 單一文件要求和查詢要求的上限為 10 項。
  • 多文件的讀取作業、交易和批次寫入作業的上限為 20 項。上述限制 (10 個) 亦適用於各項作業。

    舉例來說,假設您建立的批次寫入要求有 3 項寫入作業,而您的安全性規則會使用 2 項文件存取呼叫來驗證各項寫入作業。此時,每項寫入作業都會使用 2 個存取呼叫 (上限為 10 個),而批次寫入要求則會使用 6 個存取呼叫 (共 20 個)。

超過任一項限制會導致權限遭拒的錯誤。系統可能會快取部分文件存取呼叫,已快取的呼叫不會計入限制中。

如要深入瞭解這些限制對交易和批次寫入作業的影響,請參閱保護不可拆分的作業指南。

存取呼叫和定價

使用這些函式會在資料庫中執行讀取作業,這表示即使規則拒絕要求,系統還是會向您收取讀取文件的費用。如需更詳細的帳單資訊,請參閱 Cloud Firestore 定價

自訂函式

隨著安全性規則變得更加複雜,您可能會想要將多組條件納入函式中,以便在規則集內重複使用。安全性規則支援自訂函式。自訂函式的語法有點像 JavaScript,但安全性規則函式是以網域特定語言編寫,但有一些重要限制:

  • 函式只能含有單一 return 陳述式。且不得包含任何額外的邏輯。例如,執行個體無法執行迴圈或呼叫外部服務。
  • 函式可以從定義範圍內自動存取函式和變數。舉例來說,在 service cloud.firestore 範圍中定義的函式可存取 resource 變數和內建函式,例如 get()exists()
  • 函式可能會呼叫其他函式,但可能不會重複。呼叫堆疊總深度上限為 10。
  • 在規則版本 v2 中,函式可使用 let 關鍵字定義變數。函式最多可以有 10 個允許繫結,但結尾必須是傳回陳述式。

function 關鍵字定義函式,且必須使用零個或多個引數。例如,您可能想要將上述範例中使用的兩種條件類型合併為單一函式:

service cloud.firestore {
  match /databases/{database}/documents {
    // True if the user is signed in or the requested data is 'public'
    function signedInOrPublic() {
      return request.auth.uid != null || resource.data.visibility == 'public';
    }

    match /cities/{city} {
      allow read, write: if signedInOrPublic();
    }

    match /users/{user} {
      allow read, write: if signedInOrPublic();
    }
  }
}

在安全性規則中使用函式,可讓規則隨著規則的複雜度增加而維護。

規則不是篩選器

保護資料並開始寫入查詢後,請注意安全性規則並非篩選功能。您無法針對集合中的所有文件編寫查詢,並預期 Cloud Firestore 只會傳回目前用戶端有權存取的文件。

例如,選擇以下安全性規則:

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow the user to read data if the document has the 'visibility'
    // field set to 'public'
    match /cities/{city} {
      allow read: if resource.data.visibility == 'public';
    }
  }
}

已拒絕:這項規則會拒絕下列查詢,因為結果集可能包含 visibility 不是 public 的文件:

網站
db.collection("cities").get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
    });
});

允許:這項規則允許下列查詢,因為 where("visibility", "==", "public") 子句保證結果集符合規則的條件:

網站
db.collection("cities").where("visibility", "==", "public").get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            console.log(doc.id, " => ", doc.data());
        });
    });

Cloud Firestore 安全性規則會根據查詢的潛在結果來評估每筆查詢,如果能傳回用戶端無權讀取的文件,則要求失敗。查詢必須遵循安全性規則設定的限制。如要進一步瞭解安全性規則和查詢,請參閱「安全地查詢資料」。

後續步驟