首页 > 解决方案 > 为具有异常字段的动态和静态节点创建 Firebase 规则

问题描述

我有静态节点,例如(用户-技术-服务-订单),

例如(技术)我创建(写入限制)只使用相同的技术,除了 3 个字段被允许为所有经过身份验证的用户写入。

我可以这样做:

    {
    "rules": {
     //
    "phonenumbers":{
    ".read": true,
    ".write":  "auth !== null"
    },
    "services":{
    ".read": true,
    ".write":  "auth !== null"
    },
    "subservices":{
    ".read": true,
   ".write":  "auth !== null"
    },
    "ChargeRecordsProv":{
    ".read": "auth !== null",
    ".write":  "auth !== null"
  },
    "ChargeRecordsUsers":{
    ".read": "auth !== null",
     ".write":  "auth !== null"
  },
    "ExchangeRecords":{
    ".read": "auth !== null",
    ".write":  "auth !== null"
  },
     "directions":{
    ".read": "auth !== null",
    ".write":  "auth !== null"
  },
     "orders":{
    ".read": "auth !== null",
     ".write":  "auth !== null"
  },
     "setting":{
    ".read": "auth !== null",
  },
     "technical":{
    ".read": "auth !== null",
      "$user_id": {
    ".write": "$user_id === auth.uid"
     },
     "balancepro": {
    ".write": "auth !== null"
     },
     "ratingNumClinets": {
    ".write": "auth !== null"
     },
     "ratingDegree": {
    ".write": "auth !== null"
     },
     "statusProv": {
    ".write": true
     }
  },
     "users":{
    ".read": "auth !== null",
      "$user_id": {
    ".write": "$user_id === auth.uid"
  }
  }
    }
  }

这对我的静态节点很有用。

问题是:

我有一个动态节点,比如 (Technicians_Carpenter_location),他的名字不知道,因为它取决于管理员可以设置的内容。

这些动态节点将不允许按照我之前的规则进行读写。如果我添加这样的公共规则:

      ".read": "auth !== null",
      ".write":  "auth !== null"

它可以读写,但这会影响静态节点的所有先前规则并且不起作用。

所以,请提出建议,我能做什么?

标签: firebasefirebase-realtime-databasefirebase-security

解决方案


我认为您正在寻找通配符规则,它匹配所有其他规则不匹配的子节点。此类规则的一个简单示例是:

{
  "rules": {
    "profiles": {
      "$profileid": {
        ".read": true
      }
    }
  }
}

使用上述规则,任何人都可以阅读特定的个人资料(例如/profiles/puf),但没有人可以一次阅读所有个人资料(/profiles)。

因此,在您的情况下,如果您想向特定命名节点授予特定权限,并向所有其他节点授予一组通用权限,您需要向当前节点添加通配符。像这样的东西:

{
  "rules": {
    "phonenumbers":{
      ".read": true,
      ".write":  "auth !== null"
    },
    ...
    "$other": {
      ".read": "auth !== null",
      ".write":  "auth !== null"
    }
  }
}

推荐阅读