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

Firestore规则配置问题:管理员权限与用户数据查询报错

问题分析与解决方案

问题根源

你当前的Firestore规则逻辑存在错误:resource.data.roles == 'admin'判断的是被访问文档的角色为admin,而非发起请求的用户是admin。这就导致:

  • 查询admin角色的文档时,每个匹配的文档自身roles是admin,规则校验通过;
  • 查询customer角色的文档时,文档自身roles是customer,不满足规则里的resource.data.roles == 'admin'条件,因此触发「权限缺失或不足」错误。

修正后的Firestore规则

需要调整规则逻辑,改为判断当前请求用户的profile角色是admin,同时保留用户本人读取自身数据的权限:

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    match /profiles/{profile} {   
      allow create;
      allow read: if request.auth != null && (
        // 用户本人可读自身数据
        request.auth.uid == profile ||
        // 管理员可读取所有数据:获取当前用户的profile文档,检查其roles为admin
        get(/databases/$(database)/documents/profiles/$(request.auth.uid)).data.roles == 'admin'
      );
      // 若需管理员拥有写权限,可添加如下逻辑
      allow write: if request.auth != null && (
        request.auth.uid == profile ||
        get(/databases/$(database)/documents/profiles/$(request.auth.uid)).data.roles == 'admin'
      );
    }
  }
}

关键说明

  1. get(/databases/$(database)/documents/profiles/$(request.auth.uid))会获取当前登录用户的profile文档,通过其roles字段判断是否为管理员;
  2. 规则保留了request.auth.uid == profile,确保普通用户仍能读取自己的profile数据;
  3. 若需要管理员拥有修改、删除等写操作权限,可参照read的逻辑添加对应的allow write规则。

验证查询

你的查询代码无需修改,当以admin角色用户登录时,执行以下代码即可正常获取所有customer角色的用户:

const getDocument = async()=>{
    const q = query(collection(db, 'profiles'), where ('roles', '==', "customer"))
    const docSnap = await getDocs(q)
    docSnap?.forEach((doc)=>{
      setProfile(doc.data())
    })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:42:44