在 Firebase 中管理用戶

創建用戶

您可以通過調用CreateUserWithEmailAndPassword方法或使用聯合身份提供商(例如Google Sign-InFacebook Login )首次登錄用戶來在您的 Firebase 項目中創建一個新用戶。

您還可以在用戶頁面上的Firebase 控制台的身份驗證部分創建新的密碼驗證用戶。

獲取當前登錄的用戶

獲取當前用戶的推薦方法是在 Auth 對像上設置偵聽器:

class MyAuthStateListener : public firebase::auth::AuthStateListener {
 public:
  void OnAuthStateChanged(firebase::auth::Auth* auth) override {
    firebase::auth::User user = auth->current_user();
    if (user.is_valid()) {
      // User is signed in
      printf("OnAuthStateChanged: signed_in %s\n", user.uid().c_str());
    } else {
      // User is signed out
      printf("OnAuthStateChanged: signed_out\n");
    }
    // ...
  }
};
// ... initialization code
// Test notification on registration.
MyAuthStateListener state_change_listener;
auth->AddAuthStateListener(&state_change_listener);

通過使用偵聽器,您可以確保在獲取當前用戶時 Auth 對像不處於中間狀態(例如初始化)。

您還可以通過調用current_user獲取當前登錄的用戶。如果用戶未登錄,則用戶的is_valid方法將返回 false。

保留用戶的憑據

用戶登錄後,用戶的憑據將存儲在本地密鑰庫中。可以通過註銷用戶來刪除用戶憑據的本地緩存。密鑰庫是特定於平台的:

獲取用戶的個人資料

要獲取用戶的個人資料信息,請使用firebase::auth::User實例的訪問器方法。例如:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  std::string name = user.display_name();
  std::string email = user.email();
  std::string photo_url = user.photo_url();
  // 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 firebase::auth::User::Token() instead.
  std::string uid = user.uid();
}

獲取用戶特定於提供商的個人資料信息

要獲取從鏈接到用戶的登錄提供程序檢索到的配置文件信息,請使用ProviderData方法。例如:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  for (auto it = user.provider_data().begin();
       it != user.provider_data().end(); ++it) {
    firebase::auth::UserInfoInterface profile = *it;
    // Id of the provider (ex: google.com)
    std::string providerId = profile.provider_id();

    // UID specific to the provider
    std::string uid = profile.uid();

    // Name, email address, and profile photo Url
    std::string name = profile.display_name();
    std::string email = profile.email();
    std::string photoUrl = profile.photo_url();
  }
}

更新用戶的個人資料

您可以使用UpdateUserProfile方法更新用戶的基本個人資料信息(用戶的顯示名稱和個人資料照片 URL)。例如:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  firebase::auth::User::UserProfile profile;
  profile.display_name = "Jane Q. User";
  profile.photo_url = "https://example.com/jane-q-user/profile.jpg";
  user.UpdateUserProfile(profile).OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        // We are probably in a different thread right now.
        if (completed_future.error() == 0) {
          printf("User profile updated.");
        }
      },
      nullptr);  // pass user_data here.
}

設置用戶的電子郵件地址

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

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.UpdateEmail("user@example.com")
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            // We are probably in a different thread right now.
            if (completed_future.error() == 0) {
              printf("User email address updated.");
            }
          },
          nullptr);
}

向用戶發送驗證郵件

您可以使用SendEmailVerification方法向用戶發送地址驗證電子郵件。例如:

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.SendEmailVerification().OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        // We are probably in a different thread right now.
        if (completed_future.error() == 0) {
          printf("Email sent.");
        }
      },
      nullptr);
}

您可以在電子郵件模板頁面上自定義在Firebase 控制台的身份驗證部分中使用的電子郵件模板。請參閱 Firebase 幫助中心的電子郵件模板

設置用戶密碼

您可以使用UpdatePassword方法設置用戶密碼。例如:

firebase::auth::User user = auth->current_user();
std::string newPassword = "SOME-SECURE-PASSWORD";

if (user.is_valid()) {
  user.UpdatePassword(newPassword.c_str())
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            // We are probably in a different thread right now.
            if (completed_future.error() == 0) {
              printf("password updated.");
            }
          },
          nullptr);
}

發送密碼重置電子郵件

您可以使用SendPasswordResetEmail方法向用戶發送密碼重置電子郵件。例如:

std::string emailAddress = "user@example.com";

auth->SendPasswordResetEmail(emailAddress.c_str())
    .OnCompletion(
        [](const firebase::Future<void>& completed_future,
           void* user_data) {
          // We are probably in a different thread right now.
          if (completed_future.error() == 0) {
            // Email sent.
          } else {
            // An error happened.
            printf("Error %d: %s", completed_future.error(),
                   completed_future.error_message());
          }
        },
        nullptr);

您可以在電子郵件模板頁面上自定義在Firebase 控制台的身份驗證部分中使用的電子郵件模板。請參閱 Firebase 幫助中心的電子郵件模板

您還可以從 Firebase 控制台發送密碼重置電子郵件。

刪除用戶

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

firebase::auth::User user = auth->current_user();
if (user.is_valid()) {
  user.Delete().OnCompletion(
      [](const firebase::Future<void>& completed_future, void* user_data) {
        if (completed_future.error() == 0) {
          // User deleted.
        } else {
          // An error happened.
          printf("Error %d: %s", completed_future.error(),
                 completed_future.error_message());
        }
      },
      nullptr);
}

您還可以從用戶頁面上的Firebase 控制台的身份驗證部分刪除用戶。

重新驗證用戶

某些安全敏感操作(例如刪除帳戶設置主要電子郵件地址更改密碼)需要用戶最近登錄。如果您執行其中一個操作,而用戶登錄時間太早,則行動失敗。

發生這種情況時,通過從用戶那裡獲取新的登錄憑據並將憑據傳遞給Reauthenticate來重新驗證用戶。例如:

firebase::auth::User user = auth->current_user();

// 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.is_valid()) {
  user.Reauthenticate(credential)
      .OnCompletion(
          [](const firebase::Future<void>& completed_future,
             void* user_data) {
            if (completed_future.error() == 0) {
              printf("User re-authenticated.");
            }
          },
          nullptr);
}

導入用戶帳戶

您可以使用 Firebase CLI 的auth:import命令將用戶帳戶從文件導入您的 Firebase 項目。例如:

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