【问题标题】:Firebase.auth.currentUser is never nullFirebase.auth.currentUser 永远不会为空
【发布时间】:2021-09-09 16:05:10
【问题描述】:

我需要从 Firebase.auth.currentUser 函数接收“null”值,但它返回一些默认用户。

val auth = Firebase.auth
val currentUser = auth.currentUser
if (currentUser != null) {
        val action = SignInFragmentDirections.actionSignInFragmentToTransactionsFragment(currentUser)
        findNavController().navigate(action)
    }

由于auth.currentUser 从不返回null,我的应用程序总是转到另一个屏幕并且不允许注册新用户。 为什么会发生这种情况?我在调用auth.сurrentUser 时如何获得null

【问题讨论】:

  • 您必须注销用户才能使其为空。
  • 我在 Firebase 中创建了一个用户,但之后我在 Firebase 控制台中删除了它们,但 auth.currentUser 返回非空...
  • 请不要将您的问题的状态放在未来的标题中。在 Stack Overflow 上,系统会根据自动获得的答案跟踪问题的状态。
  • 哦,我不知道,谢谢你的信息。

标签: android firebase kotlin firebase-authentication


【解决方案1】:

我想通了 - 如果我登录应用程序并且没有调用 auth.signOut 方法 - 我只从 Firebase 控制台删除了该帐户,因此身份验证令牌在本地保存了一段时间,因此auth.currentUser 返回非空值。当我删除应用程序(并稍后在我的应用程序中添加 signOut 逻辑)并重新安装它时,一切正常。

【讨论】:

    【解决方案2】:

    “不允许注册新用户”

    在我看来,您正在尝试使用 Android SDK 创建多个用户,但它不是为此而构建的。登录后,您必须注销才能创建另一个用户,因为只有一个用户可以登录单个应用程序(至少单个 Firebase 项目)。

    如果您想创建多个帐户,则可以直接从 Firebase 控制台执行此操作。但是,如果您的应用程序旨在供可以创建新帐户的管理员或特权用户使用,并且您不想让他们访问 Firebase 控制台,那么您将不得不使用类似 Cloud functions 或您自己的服务器的东西。

    在那里您可以使用Firebase Admin SDK 创建新用户。一个简单的函数可能如下所示:

    exports.createNewUser = functions.https.onCall((data, context) => {
      return admin
      .auth()
      .createUser({
        email: data.email
      })
      .then((userRecord) => {
        // See the UserRecord reference doc for the contents of userRecord.
        console.log('Successfully created new user:', userRecord.uid);
        return userRecord.uid
      })
      .catch((error) => {
        console.log('Error creating new user:', error);
      });
    });
    

    您可以像这样从您的应用中调用该函数:

    private fun createUser(name: String, email: String): Task<String> {
        // Create the arguments to the callable function.
        val data = hashMapOf(
            "name" to name,
            "email" to email
        )
    
        return functions
                .getHttpsCallable("createNewUser")
                .call(data)
                .continueWith { task ->
                    val result = task.result?.data as String
                }
    }
    

    您可以阅读有关可调用函数的更多信息here

    请注意,我只是在云函数中运行了 create user 方法,但理想情况下,您应该检查哪个用户正在调用该函数(context.auth 有信息)并确保只有授权用户才能使用该函数。

    【讨论】:

    • 感谢您的详细解答!但我的意思是 auth.currentUser 永远不会为空,因此我的“SignInScreen”没有查看,因为 if 运算符是 true 并且它的主体导航到另一个活动:)
    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多