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

Android Studio实现Firebase实时数据库仅交易双方可见交易帖

解决方案

1. 调整数据结构

给每个交易帖子新增allowedUserIds字段,用来存储允许查看该帖子的用户UID数组。示例结构如下:

{
  "posts": {
    "postId_123": {
      "itemName": "二手笔记本",
      "publisherId": "user_456",
      "quoteUserId": "user_789",
      "allowedUserIds": ["user_456", "user_789"],
      // 其他帖子字段...
    }
  }
}

也可以拆分节点,把公开帖子和私密帖子分开存储:

{
  "publicPosts": {
    // 未接受报价的帖子
  },
  "privatePosts": {
    "postId_123": {
      "itemName": "二手笔记本",
      "publisherId": "user_456",
      "quoteUserId": "user_789",
      // 其他帖子字段...
    }
  }
}

2. 配置Firebase实时数据库安全规则

通过安全规则限制只有授权用户能读取对应帖子:

方案一(基于allowedUserIds字段)

{
  "rules": {
    "posts": {
      "$postId": {
        ".read": "auth != null && data.child('allowedUserIds').val().includes(auth.uid)",
        ".write": "auth != null && (data.child('publisherId').val() == auth.uid)"
      }
    }
  }
}
  • .read规则:验证用户已登录,且当前用户UID在帖子的allowedUserIds数组中
  • .write规则:仅发布者能修改帖子

方案二(拆分节点)

{
  "rules": {
    "publicPosts": {
      ".read": "auth != null",
      "$postId": {
        ".write": "auth != null && (data.child('publisherId').val() == auth.uid || !data.exists())"
      }
    },
    "privatePosts": {
      "$postId": {
        ".read": "auth != null && (data.child('publisherId').val() == auth.uid || data.child('quoteUserId').val() == auth.uid)",
        ".write": "auth != null && data.child('publisherId').val() == auth.uid"
      }
    }
  }
}
  • publicPosts:所有登录用户可读取,仅发布者可创建/修改
  • privatePosts:仅发布者和报价者可读取,仅发布者可修改

3. 业务逻辑实现

  • 发布帖子时:初始化allowedUserIds为发布者UID(方案一),或存入publicPosts节点(方案二)
  • 接受报价时:
    • 方案一:更新帖子的allowedUserIds数组,添加报价者UID
    • 方案二:将帖子从publicPosts移动到privatePosts节点,并记录报价者UID

内容的提问来源于stack exchange,提问作者Paulo Trevor Regacho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:20:35