Quản lý người dùng trong Firebase

Tạo người dùng

Bạn có thể tạo người dùng mới theo các cách sau:

  • Từ ứng dụng của bạn: Tạo người dùng mới trong dự án Firebase bằng cách gọi phương thức CreateUserWithEmailAndPassword hoặc bằng cách đăng nhập người dùng lần đầu tiên bằng một nhà cung cấp danh tính liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập bằng Facebook.

  • Trong bảng điều khiển Firebase: Tạo một người dùng mới được xác thực bằng mật khẩu trong thẻ Bảo mật > Xác thực > Người dùng.

Lấy người dùng hiện đã đăng nhập

Cách được đề xuất để lấy người dùng hiện tại là đặt một trình nghe trên đối tượng 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);

Bằng cách sử dụng một trình nghe, bạn đảm bảo rằng đối tượng Auth không ở trạng thái trung gian (chẳng hạn như trạng thái khởi tạo) khi bạn nhận được người dùng hiện tại.

Bạn cũng có thể lấy người dùng hiện đang đăng nhập bằng cách gọi current_user. Nếu người dùng chưa đăng nhập, phương thức is_valid của người dùng sẽ trả về giá trị false.

Lưu trữ thông tin đăng nhập của người dùng

Thông tin đăng nhập của người dùng sẽ được lưu trữ trong kho khoá cục bộ sau khi người dùng đăng nhập. Bạn có thể xoá bộ nhớ đệm cục bộ của thông tin đăng nhập người dùng bằng cách đăng xuất người dùng. Kho khoá dành riêng cho từng nền tảng:

Lấy hồ sơ của người dùng

Để lấy thông tin hồ sơ của người dùng, hãy sử dụng các phương thức truy cập của một phiên bản firebase::auth::User. Ví dụ:

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();
}

Lấy thông tin hồ sơ dành riêng cho nhà cung cấp của người dùng

Để nhận thông tin hồ sơ được truy xuất từ các nhà cung cấp dịch vụ đăng nhập được liên kết với người dùng, hãy sử dụng phương thức ProviderData. Ví dụ:

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();
  }
}

Cập nhật hồ sơ của người dùng

Bạn có thể cập nhật thông tin cơ bản trong hồ sơ của người dùng (tên hiển thị và URL ảnh hồ sơ của người dùng) bằng phương thức UpdateUserProfile. Ví dụ:

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.
}

Đặt địa chỉ email của người dùng

Bạn có thể đặt địa chỉ email của người dùng bằng phương thức UpdateEmail. Ví dụ:

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);
}

Gửi email xác minh cho người dùng

Bạn có thể gửi email xác minh địa chỉ cho người dùng bằng phương thức SendEmailVerification. Ví dụ:

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);
}

Bạn có thể tuỳ chỉnh mẫu email được dùng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Xem Mẫu email trong Trung tâm trợ giúp của Firebase.

Đặt mật khẩu cho người dùng

Bạn có thể đặt mật khẩu cho người dùng bằng phương thức UpdatePassword. Ví dụ:

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);
}

Gửi email đặt lại mật khẩu

Bạn có thể gửi email đặt lại mật khẩu cho người dùng bằng phương thức SendPasswordResetEmail. Ví dụ:

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);

Bạn có thể tuỳ chỉnh mẫu email được dùng trong thẻ Bảo mật > Xác thực > Mẫu của bảng điều khiển Firebase. Xem Mẫu email trong Trung tâm trợ giúp của Firebase.

Bạn cũng có thể gửi email đặt lại mật khẩu từ bảng điều khiển Firebase.

Xóa người dùng

Bạn có thể xoá tài khoản người dùng bằng phương thức Delete. Ví dụ:

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);
}

Bạn cũng có thể xoá người dùng trong bảng điều khiển Firebase trong thẻ Bảo mật > Xác thực > Người dùng.

Xác thực lại người dùng

Một số hành động nhạy cảm về bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chínhthay đổi mật khẩu) yêu cầu người dùng phải đăng nhập gần đây. Nếu bạn thực hiện một trong những thao tác này và người dùng đã đăng nhập quá lâu, thì thao tác sẽ không thành công.

Khi điều này xảy ra, hãy xác thực lại người dùng bằng cách lấy thông tin đăng nhập mới từ người dùng và truyền thông tin đăng nhập đó đến Reauthenticate. Ví dụ:

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);
}

Nhập tài khoản người dùng

Bạn có thể nhập tài khoản người dùng từ một tệp vào dự án Firebase bằng cách sử dụng lệnh auth:import của Firebase CLI. Ví dụ:

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