Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Firebase to securely share presence data within a specific group?

In my application I have a number of different user groups, such as chat rooms and specific projects.

How can I allow the users in those groups to share their presence data, and see the presence of every other user in the group, but keep that data private from the outside world?

like image 774
Rob DiMarco Avatar asked Feb 26 '13 00:02

Rob DiMarco


1 Answers

First, you'll need to begin authenticating your users by using one of the supported Firebase authentication mechanisms. More information about authentication in Firebase is available at https://www.firebase.com/docs/security/authentication.html.

Once you have begun authenticating users, your users' secure, verified user data will be available to you in your security rules via the auth variable. Let's assume that you have authenticated users and each user has a unique id, accessible via auth.uid.

For sharing group presence, I would recommend storing your data using a structure such as:

/groups/<group-id>/users/<user-id>/<presence-status>

Using this structure, you could write security rules that would make presence data globally private while user's could only view the presence state for each user in groups they're permitted to and only edit their own user's state. Here's an example security ruleset that enforces these restrictions:

{
  "groups": {
    "$groupid": {
      // Users can view the presence state of users in this group if they
      // are authenticated and listed in the group themselves.
      ".read": "auth != null && data.child('users').hasChild(auth.uid)"
      "users": {
        "$userid": {
          // Users can update only their individual account data.
          ".write": "auth != null && $userid == auth.uid && newData.val() != null"
        }
      }
    }
  }
}

In the above example, only users in /groups/<group-id>/users/ have permission to see the presence data for the group, and each user can only modify their individual data. User can read / write only to their individual user node.

To extend this a bit further, let's say that you have a special class of users that are the only ones allowed to create groups. You could include the user's permission level when generating the authentication tokens (for the example below, we'll set isAdmin=true), and grant that special level of access using updated security rules. For example, if only certain users are allowed to create groups, you could update the .write rule under $groupid to look like:

"$groupid": {
  // Only admins can create new groups.
  ".write": "auth != null && auth.isAdmin === true"
  //...
}
like image 139
Rob DiMarco Avatar answered Oct 25 '22 08:10

Rob DiMarco