javascriptfirebasefirebase-realtime-databaseuser-presence

Firebase Realtime Database Presence Not Working


From the documentation, I am doing this:

    var currentUser;
    firebase.auth().onAuthStateChanged(function(user) {
      if (user && user.emailVerified) {
        currentUser = user;
        setPresence();
      }
    });
    function setPresence() {
      var myConnectionsRef = firebase.database().ref('users/' + currentUser.uid + '/connections');
      var connectedRef = firebase.database().ref('.info/connected');
      connectedRef.on('value', function(snap) {
        if (snap.val() === true) {
          var con = myConnectionsRef.push();
          con.onDisconnect().remove();
          con.set("profile");
        }
      });
    }

I do this on every page, but it does not seem to be working on the profile page. Here is what I see in the DB: enter image description here

And this is not a one-off. Almost all users have something like that. What could be the cause of this? Why would onDisconnect not trigger?

Here is the webpage if needed: magicconnects.com/profile.

Thanks so much for your help!

EDIT: Adding security rules:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

Solution

  • The problem seems to be that the token may be expired by the time the onDisconnect code runs. So you'll need to allow unauthenticated deleted of the relevant data.

    The safest way I can think of is to do that on the level of the individual connection nodes (those starting with -M...), so that one can only delete a node by knowing the key.

    That'd look like this:

    {
      "rules": {
        "users": {
          "$uid": {
            ".read": "auth != null",
            ".write": "auth != null && auth.uid == $uid"
            "$pushid": {
              ".write": "!newData.exists()"
            }
          }
        }
      }
    }
    

    Since rules are OR'ed together, the ".write": "!newData.exists()" is an extra allowance for when somebody knows the $pushid.