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 bằng cách gọi phương thức createUser hoặc bằng cách đăng nhập người dùng lần đầu tiên thông qua nhà cung cấp danh tính được 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 mới được xác thực mật khẩu từ mục Xác thực trong bảng điều khiển của Firebase, trên trang Người dùng.

Tải người dùng hiện đang đăng nhập

Bạn nên thiết lập trình nghe trên Đối tượng xác thực để lấy người dùng hiện tại:

Swift

handle = Auth.auth().addStateDidChangeListener { auth, user in
  // ...
}

Objective-C

self.handle = [[FIRAuth auth]
    addAuthStateDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
      // ...
    }];

Bằng cách sử dụng trình nghe, bạn đảm bảo rằng đối tượng Xác thực không ở trạng thái trung gian (chẳng hạn như khởi chạy) khi bạn nhận được người dùng hiện tại.

Bạn cũng có thể yêu cầu người dùng hiện đang đăng nhập bằng cách sử dụng thuộc tính currentUser. Nếu người dùng chưa đăng nhập, currentUser sẽ không có giá trị:

Swift

if Auth.auth().currentUser != nil {
  // User is signed in.
  // ...
} else {
  // No user is signed in.
  // ...
}

Objective-C

if ([FIRAuth auth].currentUser) {
  // User is signed in.
  // ...
} else {
  // No user is signed in.
  // ...
}

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 thuộc tính của thực thể FIRUser. Ví dụ:

Swift

let user = Auth.auth().currentUser
if let user = user {
  // 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 getTokenWithCompletion:completion: instead.
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  var multiFactorString = "MultiFactor: "
  for info in user.multiFactor.enrolledFactors {
    multiFactorString += info.displayName ?? "[DispayName]"
    multiFactorString += " "
  }
  // ...
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;
if (user) {
  // 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 getTokenWithCompletion:completion: instead.
  NSString *email = user.email;
  NSString *uid = user.uid;
  NSMutableString *multiFactorString = [NSMutableString stringWithFormat:@"MultiFactor: "];
  for (FIRMultiFactorInfo *info in user.multiFactor.enrolledFactors) {
    [multiFactorString appendString:info.displayName];
    [multiFactorString appendString:@" "];
  }
  NSURL *photoURL = user.photoURL;
  // ...
}

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

Để truy xuất thông tin hồ sơ 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 thuộc tính providerData. Ví dụ:

Swift

let userInfo = Auth.auth().currentUser?.providerData[indexPath.row]
cell?.textLabel?.text = userInfo?.providerID
// Provider-specific UID
cell?.detailTextLabel?.text = userInfo?.uid

Objective-C

id<FIRUserInfo> userInfo = [FIRAuth auth].currentUser.providerData[indexPath.row];
cell.textLabel.text = [userInfo providerID];
// Provider-specific UID
cell.detailTextLabel.text = [userInfo uid];

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 lớp UserProfileChangeRequest. Ví dụ:

Swift

let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = displayName
changeRequest?.commitChanges { error in
  // ...
}

Objective-C

FIRUserProfileChangeRequest *changeRequest = [[FIRAuth auth].currentUser profileChangeRequest];
changeRequest.displayName = userInput;
[changeRequest commitChangesWithCompletion:^(NSError *_Nullable error) {
  // ...
}];

Đặt địa chỉ email của người dùng

Bạn có thể thiết lập địa chỉ email của người dùng bằng phương thức updateEmail. Ví dụ:

Swift

Auth.auth().currentUser?.updateEmail(to: email) { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser updateEmail:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

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 sendEmailVerificationWithCompletion:. Ví dụ:

Swift

Auth.auth().currentUser?.sendEmailVerification { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser sendEmailVerificationWithCompletion:^(NSError *_Nullable error) {
  // ...
}];

Bạn có thể tuỳ chỉnh mẫu email được dùng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Hãy xem phần Mẫu email trong Trung tâm trợ giúp của Firebase.

Bạn cũng có thể chuyển trạng thái thông qua URL tiếp tục để chuyển hướng trở lại ứng dụng khi gửi email xác minh.

Ngoài ra, bạn có thể bản địa hoá email xác minh bằng cách cập nhật mã ngôn ngữ trên thực thể Xác thực trước khi gửi email. Ví dụ:

Swift

Auth.auth().languageCode = "fr"
// To apply the default app language instead of explicitly setting it.
// Auth.auth().useAppLanguage()

Objective-C

[FIRAuth auth].languageCode = @"fr";
// To apply the default app language instead of explicitly setting it.
// [[FIRAuth auth] useAppLanguage];

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

Swift

Auth.auth().currentUser?.updatePassword(to: password) { error in
  // ...
}

Objective-C

[[FIRAuth auth].currentUser updatePassword:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

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 sendPasswordReset. Ví dụ:

Swift

Auth.auth().sendPasswordReset(withEmail: email) { error in
  // ...
}

Objective-C

[[FIRAuth auth] sendPasswordResetWithEmail:userInput completion:^(NSError *_Nullable error) {
  // ...
}];

Bạn có thể tuỳ chỉnh mẫu email được dùng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Hãy xem phần Mẫu email trong Trung tâm trợ giúp của Firebase.

Bạn cũng có thể chuyển trạng thái thông qua URL tiếp tục để chuyển hướng trở lại ứng dụng khi gửi email đặt lại mật khẩu.

Ngoài ra, bạn có thể bản địa hoá email đặt lại mật khẩu bằng cách cập nhật mã ngôn ngữ trên thực thể Xác thực trước khi gửi email. Ví dụ:

Swift

Auth.auth().languageCode = "fr"
// To apply the default app language instead of explicitly setting it.
// Auth.auth().useAppLanguage()

Objective-C

[FIRAuth auth].languageCode = @"fr";
// To apply the default app language instead of explicitly setting it.
// [[FIRAuth auth] useAppLanguage];

Bạn cũng có thể gửi email đặt lại mật khẩu từ bảng điều khiển của 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ụ:

Swift

let user = Auth.auth().currentUser

user?.delete { error in
  if let error = error {
    // An error happened.
  } else {
    // Account deleted.
  }
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;

[user deleteWithCompletion:^(NSError *_Nullable error) {
  if (error) {
    // An error happened.
  } else {
    // Account deleted.
  }
}];

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ố thao tác nhạy cảm về bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chínhđổi mật khẩu) đòi hỏi 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 cách đây quá lâu, thì thao tác đó sẽ không thành công do lỗi FIRAuthErrorCodeCredentialTooOld. 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 đăng nhập đến reauthenticate. Ví dụ:

Swift

let user = Auth.auth().currentUser
var credential: AuthCredential

// Prompt the user to re-provide their sign-in credentials

user?.reauthenticate(with: credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

Objective-C

FIRUser *user = [FIRAuth auth].currentUser;
FIRAuthCredential *credential;

// Prompt the user to re-provide their sign-in credentials

[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
  if (error) {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}];

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