在 Firebase 中管理使用者

新增使用者

您可以透過下列方式建立新使用者:

取得目前登入的使用者

如要取得目前使用者,建議在 Auth 物件上設定事件監聽器:

Firebase.Auth.FirebaseAuth auth;
Firebase.Auth.FirebaseUser user;

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

// Track state changes of the auth object.
void AuthStateChanged(object sender, System.EventArgs eventArgs) {
  if (auth.CurrentUser != user) {
    bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
    if (!signedIn && user != null) {
      Debug.Log("Signed out " + user.UserId);
    }
    user = auth.CurrentUser;
    if (signedIn) {
      Debug.Log("Signed in " + user.UserId);
    }
  }
}

// Handle removing subscription and reference to the Auth instance.
// Automatically called by a Monobehaviour after Destroy is called on it.
void OnDestroy() {
  auth.StateChanged -= AuthStateChanged;
  auth = null;
}

使用事件監聽器,可確保在取得目前使用者時,Auth 物件不會處於初始化等中繼狀態。

您也可以呼叫 CurrentUser,取得目前登入的使用者。如果使用者未登入,CurrentUser 會傳回空值。如果使用者已登出,使用者的 IsValid() 會傳回 false。

保留使用者憑證

使用者登入後,其憑證會儲存在本機 KeyStore 中。將使用者登出,即可刪除使用者憑證的本機快取。KeyStore 視平台而定:

取得使用者個人資料

如要取得使用者的個人資料資訊,請使用 Firebase.Auth.FirebaseUser 執行個體的存取子方法。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  string name = user.DisplayName;
  string email = user.Email;
  System.Uri photo_url = user.PhotoUrl;
  // The user's Id, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server, if you
  // have one; use User.TokenAsync() instead.
  string uid = user.UserId;
}

取得使用者的特定供應商設定檔資訊

如要取得從連結至使用者的登入供應商擷取的個人資料資訊,請使用 ProviderData 方法。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  foreach (var profile in user.ProviderData) {
    // Id of the provider (ex: google.com)
    string providerId = profile.ProviderId;

    // UID specific to the provider
    string uid = profile.UserId;

    // Name, email address, and profile photo Url
    string name = profile.DisplayName;
    string email = profile.Email;
    System.Uri photoUrl = profile.PhotoUrl;
  }
}

更新使用者個人資料

您可以使用 UpdateUserProfile 方法,更新使用者的基本個人資料資訊,包括顯示名稱和個人資料相片網址。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile {
    DisplayName = "Jane Q. User",
    PhotoUrl = new System.Uri("https://example.com/jane-q-user/profile.jpg"),
  };
  user.UpdateUserProfileAsync(profile).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateUserProfileAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User profile updated successfully.");
  });
}

設定使用者的電子郵件地址

您可以使用 UpdateEmail 方法設定使用者的電子郵件地址。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.UpdateEmailAsync("user@example.com").ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User email updated successfully.");
  });
}

傳送驗證電子郵件給使用者

您可以使用 SendEmailVerification 方法,傳送地址驗證電子郵件給使用者。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.SendEmailVerificationAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendEmailVerificationAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Email sent successfully.");
  });
}

您可以在 Firebase 控制台的「Security」(安全性) >「Authentication」(驗證) >「Templates」(範本) 分頁中,自訂要使用的電子郵件範本。請參閱 Firebase 說明中心的「電子郵件範本」。

設定使用者密碼

您可以使用 UpdatePassword 方法設定使用者密碼。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
string newPassword = "SOME-SECURE-PASSWORD";
if (user != null) {
  user.UpdatePasswordAsync(newPassword).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdatePasswordAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdatePasswordAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password updated successfully.");
  });
}

傳送重設密碼電子郵件

您可以使用 SendPasswordResetEmail 方法,向使用者傳送重設密碼電子郵件。例如:

string emailAddress = "user@example.com";
if (user != null) {
  auth.SendPasswordResetEmailAsync(emailAddress).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendPasswordResetEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password reset email sent successfully.");
  });
}

您可以在 Firebase 控制台的「Security」(安全性) >「Authentication」(驗證) >「Templates」(範本) 分頁中,自訂要使用的電子郵件範本。請參閱 Firebase 說明中心的「電子郵件範本」。

您也可以透過 Firebase 控制台傳送重設密碼電子郵件。

刪除使用者

您可以使用 Delete 方法刪除使用者帳戶。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.DeleteAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("DeleteAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("DeleteAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User deleted successfully.");
  });
}

您也可以在 Firebase 控制台刪除使用者,方法是依序前往「Security」(安全性) >「Authentication」(驗證) >「Users」(使用者) 分頁。

重新驗證使用者

某些安全性敏感動作 (例如刪除帳戶、設定主要電子郵件地址和變更密碼) 需要使用者最近登入過。如果您執行其中一項操作,而使用者登入時間過久,操作就會失敗。

發生這種情況時,請向使用者取得新的登入憑證,並將憑證傳遞至 Reauthenticate,重新驗證使用者。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
Firebase.Auth.Credential credential =
    Firebase.Auth.EmailAuthProvider.GetCredential("user@example.com", "password1234");

if (user != null) {
  user.ReauthenticateAsync(credential).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("ReauthenticateAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("ReauthenticateAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User reauthenticated successfully.");
  });
}

匯入使用者帳戶

您可以使用 Firebase CLI 的 auth:import 指令,將檔案中的使用者帳戶匯入 Firebase 專案。例如:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14