在 Firebase 中管理用户

创建用户

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

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

获取当前登录的用户

如需获取当前用户,建议针对 Auth 对象设置一个监听器:

Firebase.Auth.FirebaseAuth auth;
Firebase.Auth.FirebaseUser user;

// Handle initialization of the necessary firebase modules:
void InitializeFirebase() {
  Debug.Log("Setting up Firebase Auth");
  auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
  auth.StateChanged += AuthStateChanged;
  AuthStateChanged(this, null);
}

// Track state changes of the auth object.
void AuthStateChanged(object sender, System.EventArgs eventArgs) {
  if (auth.CurrentUser != user) {
    bool signedIn = user != auth.CurrentUser && auth.CurrentUser != null;
    if (!signedIn && user != null) {
      Debug.Log("Signed out " + user.UserId);
    }
    user = auth.CurrentUser;
    if (signedIn) {
      Debug.Log("Signed in " + user.UserId);
    }
  }
}

// Handle removing subscription and reference to the Auth instance.
// Automatically called by a Monobehaviour after Destroy is called on it.
void OnDestroy() {
  auth.StateChanged -= AuthStateChanged;
  auth = null;
}

使用侦听器可确保在您获取当前用户时,Auth 对象不会处于中间状态(例如初始化)。

您也可以调用 CurrentUser 获取当前已登录的用户。如果用户并未登录,CurrentUser 将返回 null。如果用户已退出帐号,其 IsValid() 将返回 false。

保存用户的凭据

用户登录后,用户的凭据将存储在本地密钥库中。退出用户帐号即可删除本地缓存的用户凭据。密钥库是平台专用的:

获取用户个人资料

如需获取用户的个人资料信息,请使用 Firebase.Auth.FirebaseUser 实例的访问器方法。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  string name = user.DisplayName;
  string email = user.Email;
  System.Uri photo_url = user.PhotoUrl;
  // 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 User.TokenAsync() instead.
  string uid = user.UserId;
}

获取特定于提供方的用户个人资料信息

如需获取从用户已关联的登录服务提供方检索到的个人资料信息,可使用 ProviderData 方法。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  foreach (var profile in user.ProviderData) {
    // Id of the provider (ex: google.com)
    string providerId = profile.ProviderId;

    // UID specific to the provider
    string uid = profile.UserId;

    // Name, email address, and profile photo Url
    string name = profile.DisplayName;
    string email = profile.Email;
    System.Uri photoUrl = profile.PhotoUrl;
  }
}

更新用户个人资料

您可以使用 UpdateUserProfile 方法来更新用户的基本个人资料信息,即用户的显示名称和个人资料照片网址。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  Firebase.Auth.UserProfile profile = new Firebase.Auth.UserProfile {
    DisplayName = "Jane Q. User",
    PhotoUrl = new System.Uri("https://example.com/jane-q-user/profile.jpg"),
  };
  user.UpdateUserProfileAsync(profile).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateUserProfileAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateUserProfileAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User profile updated successfully.");
  });
}

设置用户电子邮件地址

您可以使用 UpdateEmail 方法设置用户的电子邮件地址。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.UpdateEmailAsync("user@example.com").ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdateEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdateEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User email updated successfully.");
  });
}

向用户发送验证电子邮件

您可以使用 SendEmailVerification 方法向用户发送地址验证电子邮件。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.SendEmailVerificationAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendEmailVerificationAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendEmailVerificationAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Email sent successfully.");
  });
}

您可以在 Firebase 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 Firebase 帮助中心的电子邮件模板

设置用户密码

您可以使用 UpdatePassword 方法设置用户密码。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
string newPassword = "SOME-SECURE-PASSWORD";
if (user != null) {
  user.UpdatePasswordAsync(newPassword).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("UpdatePasswordAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("UpdatePasswordAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password updated successfully.");
  });
}

发送重设密码电子邮件

您可以使用 SendPasswordResetEmail 方法向用户发送重设密码电子邮件。例如:

string emailAddress = "user@example.com";
if (user != null) {
  auth.SendPasswordResetEmailAsync(emailAddress).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("SendPasswordResetEmailAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("SendPasswordResetEmailAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("Password reset email sent successfully.");
  });
}

您可以在 Firebase 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 Firebase 帮助中心的电子邮件模板

您也可以从 Firebase 控制台发送重设密码电子邮件。

删除用户

您可以使用 Delete 方法删除用户帐号。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;
if (user != null) {
  user.DeleteAsync().ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("DeleteAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("DeleteAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User deleted successfully.");
  });
}

您还可以前往 Firebase 控制台的“Authentication”部分,在“用户”页面中删除用户。

重新对用户进行身份验证

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

发生这种情况时,请向用户索取新的登录凭据并将这些凭据传递给 Reauthenticate,以便对该用户重新进行身份验证。例如:

Firebase.Auth.FirebaseUser user = auth.CurrentUser;

// 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 != null) {
  user.ReauthenticateAsync(credential).ContinueWith(task => {
    if (task.IsCanceled) {
      Debug.LogError("ReauthenticateAsync was canceled.");
      return;
    }
    if (task.IsFaulted) {
      Debug.LogError("ReauthenticateAsync encountered an error: " + task.Exception);
      return;
    }

    Debug.Log("User reauthenticated successfully.");
  });
}

导入用户帐号

您可以使用 Firebase CLI 的 auth:import 命令,将用户帐号从文件导入 Firebase 项目中。例如:

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