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 của mình 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 cách sử dụng 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 Facebook .

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

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

Cách được khuyến nghị để có được người dùng hiện tại là đặ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 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ư khởi tạo—khi bạn có được người dùng hiện tại.

Bạn cũng có thể biết 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ề sai.

Duy trì thông tin xác thực của người dùng

Thông tin xác thực của người dùng sẽ được lưu trữ trong kho khóa cục bộ sau khi người dùng đăng nhập. Bộ nhớ đệm cục bộ của thông tin xác thực người dùng có thể bị xóa bằng cách đăng xuất người dùng. Kho khóa dành riêng cho 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();
}

Nhận thông tin hồ sơ cụ thể của nhà cung cấp của người dùng

Để lấy thông tin hồ sơ được truy xuất từ ​​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ể đặ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 cho người dùng một email xác minh

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ể tùy chỉnh mẫu email được sử 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 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ể tùy chỉnh mẫu email được sử 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 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ể xóa tài khoản người dùng bằng phương pháp 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ố hành động nhạy cảm về bảo mật—chẳng hạn như xóa 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 hành động này và người dùng đã đăng nhập cách đây quá lâu, hành động thất bại.

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 xác thực đó 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 của mình 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