Search code examples
firebasefirepad

Firebase JSON Security and Arrays


We'd like to use Firepad in our (mostly non-Firebase hosted) project, but we're having some troubles figuring out the best way to approach the problem.

Basically, we have many users, and each user can be a member of many groups. These "groups" each have their own Firepad which users can edit. We already have a deeply developed database structure using MySQL and don't really want to migrate our user data into Firebase right now, so we figured we'd get more creative.

We don't want users being able to edit the Firepads of groups they do not belong to. As such, as part of our authentication token, we figured we'd try sending along the user ID and the list of groups they belong to. Then, using the Firebase JSON security system, we could verify that the Firepad currently being edited is in the list of groups the user belongs to.

The problem is, the JSON system doesn't seem to accept many commands. There's no indexOf, and I can't call hasChild on the auth variable.

How can we ensure that users can only edit the Firepads of groups they belong to, without migrating all of our data to Firebase? (Or maintaining two copies of the database - one on MySQL and one on Firebase)


Solution

  • The trick here is to use an object instead of an array to store the groups (a tad awkward, I know. We'll try to make this easier / more intuitive). So in your auth token, you'd store something like:

    { userid: 'blah', groups: { 'group1': true, 'group2': true, ... } }
    

    And then in your security rules you could have something like:

    {
        ...
        "$group": {
            ".read": "auth.groups[$group] == true",
            ".write": "auth.groups[$group] == true"
        }
    }
    

    And then a user will have read/write access to /groups/<group> only if <group> is in their auth token.