Firebase用户已登录

时间:2016-07-07 14:07:01

标签: javascript firebase firebase-authentication

我有一个firebase应用程序,我可以从各种设备登录,但如果我使用同一个帐户创建一个新连接,我想断开其他连接。

我看到了这段代码,但我认为这可能适用于旧版本:

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

这看起来是正确的想法 - 如果这被调用我可以显示图形说法,"哎呀看起来像你在另一台设备上登录。"然后在允许其他连接继续的情况下触发断开连接?

1 个答案:

答案 0 :(得分:0)

这不是单独使用auth可以处理的事情,因为令牌是独立生成和存储的,并且没有可以查询的“设备会话”的概念。但是,您可以这样做:

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();
    }
  });
});

重要CAVEAT:这不是一种安全,可执行的方法,可以保证一次只能登录一台设备。相反,它是一种客户驱动的方式,通常可以实现只有一个设备登录的目标。

相关问题