Firestore Security Rules: Prevent Modification of Certain Fields

April 8, 2019

Enforce initialization of approval_status = 0 and admin_remark = null during document creation.

Ensure approval_status and admin_remark value cannot be modified (must be same as existing value)

match /item/{item_id} {
  function validCreate() {
    // fields must be initialized as such
    return request.resource.data.approval_status == 0 &&
      request.resource.data.admin_remark == null;
  }

  function validUpdate() {
    // prevent user change these fields
    return request.resource.data.approval_status == resource.data.approval_status &&
      request.resource.data.admin_remark == resource.data.admin_remark;
  }


  allow read: if true;
  // allow get: if true;
  // allow list: if true;

  allow create: if validCreate();
  allow update: if validUpdate();
  allow delete: if false;
}

In pratical usage, you probably limit modification for user, but allow admin to perform modification.

allow create: if (isUser() && validCreate()) || isAdmin();
allow update: if (isUser() && validUpdate()) || isAdmin();

NOTE: Refer firestore security rules and firestore check is admin security rules.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.