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

Firestore获取用户数据时权限不足问题求助

问题原因

你的代码是查询整个user集合,但Firestore的安全规则要求用户只能读取自己ID对应的文档。Firestore的集合查询会校验返回的所有文档是否都满足权限规则,而你的查询未做任何过滤,Firestore无法确保返回的每个文档都符合request.auth.uid == userId的条件,因此直接返回权限不足的错误。

解决方案

不要查询整个集合,而是直接查询当前用户对应的单个文档,这样就能匹配安全规则的要求。

修正后的代码
func getUser() {
    guard let uid = Auth.auth().currentUser?.uid else {
        // 处理未登录场景,比如提示用户登录
        print("用户未登录")
        return
    }
    
    db.collection("user").document(uid).getDocument { document, error in
        if let error = error {
            print("获取用户信息失败: \(error.localizedDescription)")
            return
        }
        
        guard let document = document, document.exists else {
            print("用户文档不存在")
            return
        }
        
        DispatchQueue.main.async {
            let userId = document.documentID
            let email = document["email"] as? String ?? ""
            let tokens = document["tokens"] as? Int ?? 0
            self.userInfo = [User(userId: userId, email: email, tokens: tokens)]
            // 若userInfo是单个对象而非数组,直接赋值即可
            // self.userInfo = User(userId: userId, email: email, tokens: tokens)
        }
    }
}
额外注意事项
  • 原代码中闭包里的Text("error")是SwiftUI视图组件,不能在普通函数中使用,建议替换为打印错误、更新UI状态等逻辑。
  • 安全规则里的allow write: if true存在严重安全风险,任何用户都可写入任意文档,建议修改为:allow write: if request.auth.uid == userId;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:42:51