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

Tạo người dùng

Bạn có các lựa chọn sau để tạo người dùng mới:

  • 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 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 thông tin 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 trình nghe trên đối tượng 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;
}

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 chạy) khi bạn lấy người dùng hiện tại.

Bạn cũng có thể lấy thông tin người dùng hiện đã đăng nhập bằng cách gọi CurrentUser. Nếu người dùng chưa đăng nhập, CurrentUser sẽ trả về giá trị rỗng. Nếu người dùng đã đăng xuất, IsValid() của người dùng sẽ trả về giá trị false.

Lưu giữ 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 của người dùng bằng cách đăng xuất người dùng. Kho khoá 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 thực thể Firebase.Auth.FirebaseUser. Ví dụ:

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

Lấy thông tin hồ sơ của người dùng theo nhà cung cấp cụ thể

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

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

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

Đặ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.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.");
  });
}

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

Bạn có thể tuỳ chỉnh mẫu email được sử dụng trong thẻ Security (Bảo mật) > Authentication (Xác thực) > Templates (Mẫu) của bảng điều khiển Firebase. 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.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.");
  });
}

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ụ:

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

Bạn có thể tuỳ chỉnh mẫu email được sử dụng trong thẻ Security (Bảo mật) > Authentication (Xác thực) > Templates (Mẫu) của bảng điều khiển Firebase. 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 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.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.");
  });
}

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 liên quan đến bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chính và thay đổ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 quá lâu, thì hành động đó 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à chuyển thông tin đăng nhập đó đến Reauthenticate. Ví dụ:

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

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 Giao diện dòng lệnh (CLI) của Firebase. Ví dụ:

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