You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Storage安全规则报错:database变量及get函数问题求助

修正Firebase Storage安全规则中的管理员权限问题

报错原因解析

  • Invalid variable name: database
    Firebase Storage安全规则里没有内置database变量,你用$(database)引用数据库ID是错误的。访问Firestore必须明确指定数据库ID,默认数据库ID为(default)。

  • get函数未被识别
    这个错误是路径格式无效导致的——因为$(database)变量不存在,get()的路径不合法,规则引擎无法识别正确的调用格式。规则版本2中get()函数是合法的,但必须使用正确的Firestore文档路径。

  • 隐藏问题:规则匹配顺序错误
    原代码中match /{allPaths=**}放在了/invoices/...规则前面,而Storage规则是从上到下匹配,匹配到即停止,这会导致后面的/invoices/...规则永远无法生效,必须把更具体的规则放在通用规则之前。

修正后的完整代码

rules_version = '2';

service firebase.storage {
  match /b/{bucket}/o {
  
    function isAdmin(userId) {
      // 用默认数据库ID访问Firestore的用户文档
      return get(/databases/(default)/documents/users/$(userId)).data.role == "admin";
    }
   
    // 具体路径规则优先
    match /invoices/{userId}/{soldeUid}/{fileName} {
      allow write: if request.auth != null
                   && request.auth.uid == userId
                   && soldeUid.matches("^[a-zA-Z0-9_-]*$")
                   && fileName.matches("^[a-zA-Z0-9_.-]*$");
      allow read: if request.auth != null
                  && request.auth.uid == userId;
    }

    // 通用规则放在最后,匹配所有其他路径
    match /{allPaths=**} {
      allow read, write: if isAdmin(request.auth.uid);
    }
  }
}

额外说明

  • 确保Firestore中users/{userId}文档存在role字段,且管理员用户的该字段值为"admin"。
  • 若使用自定义ID的Firestore数据库,将代码中的(default)替换为实际数据库ID即可。

内容的提问来源于stack exchange,提问作者Layer8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:01:27