简体   繁体   中英

Firebase User Already Logged In

I have a firebase app that I can log into from various devices, but I'd like to disconnect the other connections if I make a new one using the same account.

I saw this bit of code but I think this might be for the old version:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

This looks like the right idea - if this gets called I could show a graphic saying, "Oops looks like you signed in on another device." then fire a disconnect while allowing the other connection to proceed?

This isn't something you'll be able to handle with auth alone, as the tokens are generated and stored independently and there's no concept of "device sessions" that can be queried against. However, you could do something like this:

var deviceId = generateARandomDeviceIDAndStoreItInLocalStorage();

firebase.auth().signInWithPopup(/* ... */).then(function(user) {
  var userRef = firebase.database().ref('users').child(user.uid);
  return userRef.update({
    deviceId: deviceId
  });
});

firebase.auth().onAuthStateChanged(function(user) {
  var userRef = firebase.database().ref('users').child(user.uid);
  userRef.child('deviceId').on('value', function(snap) {
    if (snap.val() !== deviceId) {
      // another device has signed in, let's sign out
      firebase.auth().signOut();
    }
  });
});

IMPORTANT CAVEAT: This is not a secure, enforceable way to guarantee only one device is logged in at once. Rather it is a client-driven way to generally achieve the goal of only one device being signed in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM