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:

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

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.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 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.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 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.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ể 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.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ể 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.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ể 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.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 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