1

So, I have an app that has a messaging feature, where two users can message each other. I am structuring my data in the "messages" node, where each node are the message threads between two users. Each node is named after the two uid's of the two users who are communicating, sorted alphabetically.
For example,
if user (dd77gg) and user (zz22ss) are in a conversation, the node would be named "dd77ggzz22ss". I know you can grant access in Security Rules by doing

{
      "rules": {
        "messages": {
          "$uid": {
            ".read": "$uid === auth.uid",
            ".write": "$uid === auth.uid"
          }
        }
      }
    }

But, in my case, the nodes are not simply named $uid, but rather two uid's merged together. So, my question is, how would I simply grant access, only if the current user's uid is found somewhere in the node name?

John Leonardo
  • 598
  • 3
  • 23

1 Answers1

2

First of all do not sort your uids alphabetically, this may seem like a good idea but it is not deterministic. For example. Say the two uids were 'cat' and 'bca'. Sorting them alphabetically would give you 'aabcct'. Now suppose you have another two uids: 'cat' and 'cba'. If you were to sort them you will get the same concatenation of uids, you will get aabbcct. This will cause previous conversation data to be overwritten. Concatenating two uids is actually the best way to go. You do not need to sort them, you just have to have a determenistic way of concatenating them. Ie: who's uid should I place first.

Now to answer your question you could just use the contains method in the firebase rule.

{
      "rules": {
        "messages": {
          "$uid": {
            ".read": "$uid.contains(auth.uid),
            ".write": "$uid.contains(auth.uid)"
          }
        }
      }
    }

You just check if it contains one of the users id, if it does then they can read it of course. I hope this helps.

Umar Karimabadi
  • 960
  • 8
  • 20
  • 1
    My standard recommendation is to name the room after the lexicographically ordered UID. See my answer here: http://stackoverflow.com/questions/33540479/best-way-to-manage-chat-channels-in-firebase The two examples you give would become `bca_cat` (`_` for readability) and `cat_cba`. By concatenating the UIDs, you ensure that the same participants will end up in the same room and duplicates are prevented. Doing a character by character sort would indeed not work, but I don't think OP indicated in any way that they were doing a character sort. – Frank van Puffelen Mar 19 '17 at 00:05
  • 1
    Yh, what Puf said. Legend! (I am such a fan). Cant wait to see you in the next episode of #askFirebase. : ) – Umar Karimabadi Mar 19 '17 at 00:09