在 Firebase 中管理用户

创建用户

如需在 Firebase 项目中创建新用户,您可以调用 CreateUserWithEmailAndPassword 方法,或让用户通过 Google 登录服务或 Facebook 登录服务等联合身份提供方服务完成首次登录。

您还可以转至 Firebase 控制台的“Authentication”部分,在“用户”页面中创建以密码验证身份的新用户。

获取当前登录的用户

如需获取当前用户,建议针对 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 方法来更新用户的基本个人资料信息,即用户的显示名称和个人资料照片网址。例如:

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 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 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 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 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 控制台的“Authentication”部分,在“用户”页面中删除用户。

重新对用户进行身份验证

某些涉及安全的敏感操作(例如删除帐号设置主电子邮件地址更改密码)只能针对最近登录过的用户执行。如果您执行某项这类操作,而该用户的登录时间已经是很久之前,该操作便会失败。

发生这种情况时,请向用户索取新的登录凭据并将这些凭据传递给 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