Allow only friends of users to see each other's information?

Viewed 47

I have a users and friends collection in Firebase structured as follows:

Users:
    UID-1
        Email
        Username
    UID-2
        Email
        Username
    ...

Friends:
    FID-1
        UID-1
        UID-2
    ...

Where usernames are public but emails are private, as enforced by current rules. I want to be able to retrieve a list of the UIDs that a user is friends with securely.

I found it simple enough to enforce username and email access by specifying auth != null or auth.uid == $UID but how do I go about making it so that users can only access the Users documents that they are friends with?


Can I query the database 'internally' as part of a rule? I.e. "Only allow retrieval of this document if the user is friends with them (friend information stored at "Friends" directory)?" I am okay if the solution posed requires restructuring the data or the existing security rules.

1 Answers

I have solved this question after working on it for a while and wanted to post my solution to any having the same issue:

You can basically 'split the difference' by instead of applying a friendship based rule for users, apply a rule for reading friendships. Since UIDs are not guessable, you can assume someone querying public information about a particular one has a reason to do so. Then all you have to do is regulate access to those UIDs. I did this by only allowing the details of a friendship to be read if you were one of the parties involved.

Ex.

".read" : "auth.uid === data.child('UID-1').val() || auth.uid === data.child('UID-2').val()"

Related