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

Tạo người dùng

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 thông qua nhà cung cấp danh tính được liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập Facebook.

Bạn cũng có thể tạo người dùng mới được xác thực mật khẩu từ mục Xác thực trong bảng điều khiển của Firebase, trên trang Người dùng.

Tải người dùng hiện đang đăng nhập

Bạn nên thiết lập trình nghe trên Đối tượng xác thực để lấy người dùng hiện tại:

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 trình nghe, bạn đảm bảo rằng đối tượng Xác thực không ở trạng thái trung gian (chẳng hạn như khởi chạy) khi bạn nhận được người dùng hiện tại.

Bạn cũng có thể xem 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, thì phương thức is_valid của người dùng sẽ trả về giá trị false.

Duy 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ể đăng xuất người dùng trong bộ nhớ đệm cục bộ của thông tin xác thực 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 thực thể của 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ơ theo nhà cung cấp cụ thể của người dùng

Để lấy thông tin hồ sơ từ các trì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 hồ sơ cơ bản 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ể thiết lập đị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. Hãy xem phần Mẫu email trong Trung tâm trợ giúp của Firebase.

Đặt mật khẩu của người dùng

Bạn có thể đặt mật khẩu của 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 phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Hãy xem phần 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 của 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ể xóa người dùng khỏi phần Xác thực của bảng điều khiển Firebase, trên trang Người dùng.

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

Một số thao tác nhạy cảm về bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chínhđổi mật khẩu) đòi hỏi 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 cách đây 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 nhận thông tin đăng nhập mới từ người dùng và chuyển thông tin đăng nhập tới 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