简体   繁体   English

基于Unity的离线登录 Android Apps

[英]Offline Login for Unity-Based Android Apps

I am noob in Unity and I am trying to create an email and password authentication using Firebase. I am trying to create a scenario where if the client is offline (especially in an area where there is no connectivity), the client should be able to login offline.我是 Unity 的新手,我正在尝试使用 Firebase 创建一个 email 和密码身份验证。我正在尝试创建一个场景,如果客户端离线(尤其是在没有连接的区域),客户端应该能够离线登录。 Is there any way to do this?有什么办法吗?

Below is the code I am using which I pulled from here .下面是我从这里提取的代码。

using System;
using System.Collections.Generic;
using Firebase.Extensions;
using UnityEngine;
using UnityEngine.SceneManagement;

[CreateAssetMenu]
public class AuthManager : ScriptableObject
{
  // Firebase Authentication instance.
  protected Firebase.Auth.FirebaseAuth auth;

  // Firebase User keyed by Firebase Auth.
  protected Dictionary<string, Firebase.Auth.FirebaseUser> userByAuth =
    new Dictionary<string, Firebase.Auth.FirebaseUser>();

  // Flag to check if fetch token is in flight.
  private bool fetchingToken = false;

  // Handle initialization of the necessary firebase modules:
  public void InitializeFirebase()
  {
    Debug.Log("Setting up Firebase Auth");
    auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
    auth.StateChanged += AuthStateChanged;
    auth.IdTokenChanged += IdTokenChanged;
    AuthStateChanged(this, null);
  }

  // Track state changes of the auth object.
  void AuthStateChanged(object sender, System.EventArgs eventArgs)
  {
    Firebase.Auth.FirebaseAuth senderAuth = sender as Firebase.Auth.FirebaseAuth;
    Firebase.Auth.FirebaseUser user = null;

    if (senderAuth != null) userByAuth.TryGetValue(senderAuth.App.Name, out user);
    if (senderAuth == auth && senderAuth.CurrentUser != user)
    {
      bool signedIn = user != senderAuth.CurrentUser && senderAuth.CurrentUser != null;
      if (!signedIn && user != null)
      {
        Debug.Log("Signed out " + user.UserId);
        SceneManager.LoadScene("SignInScene");
      }
      user = senderAuth.CurrentUser;
      userByAuth[senderAuth.App.Name] = user;
      if (signedIn)
      {
        Debug.Log("Signed in " + user.DisplayName);
        DisplayDetailedUserInfo(user, 1);
        SceneManager.LoadScene("MainScene");
      }
    }
    else
    {
      SceneManager.LoadScene("SignInScene");
    }
  }

  // Track ID token changes.
  void IdTokenChanged(object sender, System.EventArgs eventArgs)
  {
    Firebase.Auth.FirebaseAuth senderAuth = sender as Firebase.Auth.FirebaseAuth;
    if (senderAuth == auth && senderAuth.CurrentUser != null && !fetchingToken)
    {
      senderAuth.CurrentUser.TokenAsync(false).ContinueWithOnMainThread(
        task => Debug.Log(String.Format("Token[0:8] = {0}", task.Result.Substring(0, 8))));
    }
  }

  // Display a more detailed view of a FirebaseUser.
  protected void DisplayDetailedUserInfo(Firebase.Auth.FirebaseUser user, int indentLevel)
  {
    string indent = new String(' ', indentLevel * 2);
    DisplayUserInfo(user, indentLevel);
    Debug.Log(String.Format("{0}Anonymous: {1}", indent, user.IsAnonymous));
    Debug.Log(String.Format("{0}Email Verified: {1}", indent, user.IsEmailVerified));
    Debug.Log(String.Format("{0}Phone Number: {1}", indent, user.PhoneNumber));
    var providerDataList = new List<Firebase.Auth.IUserInfo>(user.ProviderData);
    var numberOfProviders = providerDataList.Count;
    if (numberOfProviders > 0)
    {
      for (int i = 0; i < numberOfProviders; ++i)
      {
        Debug.Log(String.Format("{0}Provider Data: {1}", indent, i));
        DisplayUserInfo(providerDataList[i], indentLevel + 2);
      }
    }
  }

  // Display user information.
  protected void DisplayUserInfo(Firebase.Auth.IUserInfo userInfo, int indentLevel)
  {
    string indent = new String(' ', indentLevel * 2);
    var userProperties = new Dictionary<string, string> {
        {"Display Name", userInfo.DisplayName},
        {"Email", userInfo.Email},
        {"Photo URL", userInfo.PhotoUrl != null ? userInfo.PhotoUrl.ToString() : null},
        {"Provider ID", userInfo.ProviderId},
        {"User ID", userInfo.UserId}
      };
    foreach (var property in userProperties)
    {
      if (!String.IsNullOrEmpty(property.Value))
      {
        Debug.Log(String.Format("{0}{1}: {2}", indent, property.Key, property.Value));
      }
    }
  }

  // Clean up auth state and auth.
  void OnDestroy()
  {
    auth.StateChanged -= AuthStateChanged;
    auth = null;
  }
}

There is no way to validate any credentials while the user is offline, so for most providers signing in while offline is not an option.用户离线时无法验证任何凭据,因此对于大多数提供商来说,离线登录不是一种选择。 The only built-in provider that can satisfy a signIn... call while offline, is the anonymous auth provider .唯一可以在离线时满足signIn...调用的内置提供程序是匿名身份验证提供程序

This is different when the user has already signed in in the past, and is restarting the app.当用户过去已经登录并重新启动应用程序时,这是不同的。 In that scenario Firebase assumes the user is still signed in, will set the current user and fire the AuthStateListener event even while offline.在这种情况下,Firebase 假定用户仍处于登录状态,将设置当前用户并在离线时触发AuthStateListener事件。 Once the connection is reestablished it will re-validate the user credentials, to check for example if the account was suspended.重新建立连接后,它将重新验证用户凭据,例如检查帐户是否已暂停。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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