首页 > 解决方案 > 社交应用的 Firebase 规则

问题描述

我正在尝试扩展一个社交 android aap,目前它的规则是公开的,它的数据结构是这样的,

{
  "posts" : {
    "postId1" : {
      "authorId" : "abcd",
    },
    "postId2" : {
      "authorId" : "abcd",

    },
    "postId3" : {
      "authorId2" : "wxyz",

    },
    "postId4" : {
      "authorId2" : "wxyz",
    }
  }
}

我想允许经过身份验证的用户在“帖子”节点中创建和删除他自己的帖子我试过这个,

{
  "rules": {
        ".read":"auth.uid != null",
        ".write":false,
      "questions": {
      "$uid": {
        ".write": "$uid === auth.uid"
      }
    }
}}

但这不允许用户创建帖子,尽管用户可以在“帖子”节点中编辑或删除他预先存在的帖子,但似乎“帖子”节点内没有写权限。但是,如果我允许“帖子”的写权限,那么由于级联规则,每个经过身份验证的用户都可以访问其他人的数据。如何实现我想要的功能?

标签: androidfirebase-realtime-databasefirebase-security

解决方案


首先请参阅 firebase-bolt 为实时数据库编写规则:https ://github.com/firebase/bolt

该工具使编写规则变得容易。

对于您的规则,这里有一个示例,仅允许作者更新帖子:

{
  "rules": {
    ".read": "auth.uid != null",
    "posts": {
      "$postId": {
        ".write": "data.val() == null && newData.child('uid').val() == auth.uid || data.val() != null && newData.val() != null && data.child('uid').val() == auth.uid || data.val() != null && newData.val() == null && newData.child('uid').val() == auth.uid"
      },
      ".read": "auth.uid != null"
    }
  }
}

和firebase螺栓等效如下:

path / {
    read() {auth.uid != null}
}

path /posts {
    read() {auth.uid != null}
    /{postId}{
    create() { this.uid == auth.uid}
    delete() { this.uid == auth.uid}
    update() { prior(this.uid) == auth.uid}
    }
}

推荐阅读