Firebase Firestore security rules三元运算符不生效问题求助
问题原因
- 字段访问逻辑错误导致规则提前终止
Firestore安全规则中直接读取request.resource.data(也就是你提到的data())中不存在的字段会直接抛出异常、终止规则执行并返回权限拒绝,不会像Dart那样返回null。当你提交的请求中没有postcounter字段时,data().postcounter != null代码会直接报错,不会执行后续的三元else分支,所以你会观察到else分支不生效的现象。
正确的字段存在性判断需要使用in操作符,'postcounter' in data()会安全返回布尔值,不会抛出异常。 - 运算符优先级可能导致逻辑不符合预期
Firestore安全规则中&&运算符优先级高于三元运算符?:,你当前的写法实际等价于如下逻辑:
(author(userid) && data().postcounter != null) ? (data().postcounter >= 0) : (data().itemtype == 'jug')
如果你的预期逻辑是「必须先通过author(userid)校验,再根据postcounter的存在性走不同判断分支」,那现有写法存在逻辑漏洞:当author(userid)为false时,表达式会直接进入else分支,只要itemtype为jug就会通过校验,绕过了作者身份校验。
修复方案
如果你不需要绕过author校验,仅在通过作者校验后才走三元分支,修复后的代码如下:
if author(userid) && ( 'postcounter' in data() && data().postcounter != null ? data().postcounter >= 0 : data().itemtype == 'jug' )
如果你的逻辑就是允许非作者只要itemtype为jug就通过,只需要修改字段判断部分即可:
if author(userid) && 'postcounter' in data() ? data().postcounter >= 0 : data().itemtype == 'jug'
内容的提问来源于stack exchange,提问作者Noobdeveloper
相关产品推荐
相关产品推荐

