管理 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