Firebase身份验证登录必须允许单个设备登录

问题描述 投票:-1回答:1

我正在使用Firebase后端开发应用程序,我正在使用Firebase Auth登录我的应用程序。我做了所有集成,每件事和我的应用程序都运行良好。

但是我想要单个用户的单个会话,因为单个userId我可以通过多个设备登录。

所以我想限制用户,一次用户可以在单个设备中登录。

我使用自定义身份验证用户名密码登录:

Auth.auth().signIn(withCustomToken: customToken ?? "") { (user, error) in
  // ...
}

如果用户在另一台设备中使用相同的ID登录,我想显示“您已登录其他设备”的提醒。

Firebase Auth lib是否有可能用于单用户单一会话?

编辑:建议重复的问题不会完全解决我的查询虽然它有助于我理解scenireo并帮助解决我的问题。

感谢@Frenk指出这一点。

ios swift firebase firebase-authentication
1个回答
0
投票

我通过firebase身份验证对上述问题进行了大量搜索,经过大量研究后,我最终得到了以下解决方案,该解决方案按照我的要求工作。

首先firebase没有在他们的库中提供这个,所以我们需要在这里应用我们的自定义逻辑来实现我们的应用程序中的这个1会话用户登录。

第1步:您需要在数据库的根目录中添加新的子“SignIn”。

第2步:当Auth.auth().signIn()在该块中返回成功时,我们需要在下面检查用户是否已在任何其他设备中登录的标志?为此我创建了一个方法,如下所述。

func alreadySignedIn() {
        // [START single_value_read]
        let userID = Auth.auth().currentUser?.uid
        ref.child("SignIn").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value

            if let dict = snapshot.value as? [String: Any] {
                if let signedIn = dict["signIn"] as? Bool {
                    if signedIn {
                        self.signOut()
                    }
                    else {
                        // change the screen like normal
                        print("First Session of user")
                        self.writeNewUserSigin(withUserID: userID!)
                    }
                }else{
                    self.writeNewUserSigin(withUserID: userID!)
                }
            }else{
                print(snapshot)
                self.writeNewUserSigin(withUserID: userID!)
            }
        }) { (error) in
            print(error.localizedDescription)
        }
        // [END single_value_read]
    }

通过这种方法,我们检查当前用户uId在我们的SignIn Child中具有True值,如果数据在我们的数据库中有Boll值True我们需要处理它并从firebase显示一些警告和signOut。

注意:由于我们允许用户登录,而我们正在检查用户是否已登录任何其他设备,因此如果其返回True,我们需要来自firebase的SignOut()。

现在,当用户从应用程序手动签名时,最后一步

第3步:当用户点击应用程序中的SignOut按钮时,我们需要在其中更新我们的Child with False值,以便之后用户可以在任何其他设备中登录。为此,我们可以使用以下方法。

func updateUserSigIn(withUserID userID: String) {
        //Update SignIn Child with flase value on current UID
        // [START write_fan_out]

        let post = ["signIn": false]
        let childUpdates = ["/SignIn/\(userID)": post]
        let ref = Database.database().reference()
        ref.updateChildValues(childUpdates) { (error, refDatabase) in
            if (error != nil) {
                print("error \(String(describing: error))")
            }else {
                print("New user Saved successfully")
                self.signOut()
            }
        }
        // [END write_fan_out]
    }

那就是现在只有一个app用户会话允许。

希望这会有助于他人。

感谢this线程,因为我从这个答案得到了一些提示。

© www.soinside.com 2019 - 2024. All rights reserved.