Javascript Firebase用户已登录
我有一个firebase应用程序,我可以从各种设备登录,但如果我使用相同的帐户建立新连接,我想断开其他连接 我看到了这段代码,但我认为这可能适用于旧版本:Javascript Firebase用户已登录,javascript,firebase,firebase-authentication,Javascript,Firebase,Firebase Authentication,我有一个firebase应用程序,我可以从各种设备登录,但如果我使用相同的帐户建立新连接,我想断开其他连接 我看到了这段代码,但我认为这可能适用于旧版本: firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // No user is signed in. } }); 这似乎是正确的想法-如果调用此命令,我可以显示一个图形,显示“
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
这似乎是正确的想法-如果调用此命令,我可以显示一个图形,显示“Oops看起来您登录了另一个设备”。然后在允许另一个连接继续进行的同时触发断开连接?仅凭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();
}
});
});
重要注意事项:这不是一种保证一次只登录一台设备的安全、可执行的方法。相反,它是一种客户端驱动的方式,通常只实现一个设备登录的目标。这不是您能够单独使用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();
}
});
});
重要注意事项:这不是一种保证一次只登录一台设备的安全、可执行的方法。相反,它是一种客户端驱动的方式,通常可以实现仅登录一台设备的目标