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

Tạo người dùng

Bạn có thể tạo người dùng mới theo các cách sau:

  • 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 một 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 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 mộ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 một 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ư trạng thái khởi tạo) khi bạn nhận được người dùng hiện tại.

Bạn cũng có thể lấy người dùng hiện đang đă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 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ể xoá bộ nhớ đệm cục bộ của thông tin đăng nhập người dùng bằng cách đăng xuất 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 phiên bản 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ơ dành riêng cho nhà cung cấp của người dùng

Để lấy thông tin hồ sơ được truy xuất từ các 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.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 dùng trong thẻ Bảo mật > Xác thực > Mẫu của bảng điều khiển Firebase. Xem Mẫu email trong Trung tâm trợ giúp của Firebase.

Đặt mật khẩu cho người dùng

Bạn có thể đặt mật khẩu cho 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 dùng trong thẻ Bảo mật > Xác thực > Mẫu của bảng điều khiển Firebase. Xem 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 nhạy cảm về bảo mật (chẳng hạn như xoá 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 thao tác này và người dùng đã đăng nhập 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 lấy thông tin đăng nhập mới từ người dùng và truyề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 Firebase CLI. Ví dụ:

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