Firebase:如何为不同用户提供读/写访问权限?

use*_*672 4 ios firebase firebase-security firebase-authentication firebase-realtime-database

对于Firebase Database启用了基于电子邮件/密码的身份验证的用户,我们如何向登录到Firebase支持的iOS应用程序的用户授予读/写访问权限。尽管Firebase iOS SDK将身份验证api公开给创建/登录/注销用户,但是我在firebase SDK中找不到任何可以向用户提供读取或写入访问权限的api。

假设我使用api创建了两个用户user1,user2。如何授予对user1的读取访问权限和对user2的读/写访问权限。所需的访问权限在整个数据库上。

是否Security Rules只能通过(如Google Firebase控制台的“数据库”选项卡下的“规则”部分中的JSON提供)?如果是,我们如何为不同的用户创建这种读/写访问权限?如果可以通过Firebase iOS SDK进行操作,那么要使用哪个api?

谢谢

Jas*_*aat 6

一开始我很难理解,但是规则非常灵活,可以让您基于其他数据库内容访问数据。基本上,您授予对节点的访问权限,并且该授予也适用于所有子节点,并且不能从树的更深节点中删除。您可以在控制台中应用这些数据库规则,但是如果还需要使用api来设置整个数据库的规则,则必须有一个api。它们确实必须是单个文档,所以您不想对用户进行硬编码,但是您可以将它们放在隐藏且不可访问的节点中,规则可以访问它。

例如,假设您要让某人请求与其他人成为朋友,并且让其他人能够接受这两个人并将其添加到朋友列表中。您可能具有与此类似的架构:

uid
  "friends"
    friendUid1
    friendUid2
    friendUid3
  "private"
    ... some private data your friends can read
"friendRequests"
  targetUid
    requestorUid -> can be written to only by requestorUid
Run Code Online (Sandbox Code Playgroud)

第一步是向写入值friendRequests/$targetUid/$requestorUid。可以写入该节点的唯一人员是被认证为requestorUid的人员。targetUid将被授予对targetUid节点的读取访问权限,因此他们可以读取它,因为它是一个孩子,但不能写入它。

然后,您可以$requestor/friends/$targetUid根据的存在,授予对$ targetUid的写入权限friendRequests/targetUid/requestorUid。这允许接收到朋友请求的人将其OWN uid写入请求者的朋友列表,但前提是请求者已经在请求成为朋友的过程中写入了自己的uid。然后,他们会将请求者的uid写入自己的朋友列表。如果已登录用户的uid在其朋友列表中,则他们可以访问私有数据。

{
  "rules": {
    "$uid": {
      ".read": "auth.uid === $uid",
      ".write": "auth.uid === $uid",
      "friends": {
        "$friendId": {
          ".write": "root.child('friendRequests').child($friendId).child($uid) && auth.uid === $friendId"
        }
      },
      "private": {
        ".read": "data.parent().child('friends').child(auth.uid).exists()"
      }
    },  
    "friendRequests": {
      "$targetUid": {
        ".read": "auth.uid === $targetUid",
        "$requestorUid": {
          ".write": "auth.uid === $requestorUid"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

让我们使用一些“真实的” ids,并说uid 100想和uid 200成为朋友。他们会写自己的id 100作为200的请求,这是允许的,因为auth.uid将匹配$ requestorUid并匹配上一次写入规则:

ref = db.getReference("friendRequests/200/100");
ref.setValue(true);
Run Code Online (Sandbox Code Playgroud)

当用户ID 200登录时,他们可以在读取他们的所有好友请求friendRequests/200。他们看到用户100被要求成为他们的朋友,因此他们首先向添加100 users/200/friends。这是允许的,因为auth.uid将为200,并且它们具有对整个users/200节点及其所有子节点的完全读/写访问权限。

接下来,他们还可以写信,users/100/friends/200因为这条规则:

"root.child('friendRequests').child($friendId).child($uid) && auth.uid === $friendId"
Run Code Online (Sandbox Code Playgroud)

auth.uid将为200,并且检查将看到100因为friendRequests/200/100存在而被要求与200成为朋友,并且该节点只能由用户100写入。