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 vào người dùng lần đầu tiên bằng một danh tính liên kết Google, 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 mật khẩu mới từ phần Xác thực phần bảng điều khiển 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:

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 ở trong quá trình trung gian trạng thái (chẳng hạn như khởi chạy) khi bạn có người dùng hiện tại.

Bạn cũng có thể xem người dùng hiện đang đăng nhập bằng cách sử dụng currentUser thuộc tính này. 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

Để nhận thông tin hồ sơ của người dùng, hãy sử dụng các thuộc tính của một 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

Để nhận 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 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ị của người dùng và URL ảnh hồ sơ (với lớp UserProfileChangeRequest). Cho 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ỉ đến người dùng 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 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ể chuyển trạng thái thông qua tiếp tục URL để chuyển hướng trở lại vào ứ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 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. Cho 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 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 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ể chuyển trạng thái thông qua tiếp tục URL để chuyển hướng trở lại cho ứ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 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 trên 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. Cho 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ể xoá 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ư 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 cách đây quá lâu, thao tác không thành công vớ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 đăng nhập lại thông tin đăng nhập từ người dùng rồi chuyển thông tin đăng nhập đến reauthenticate. Cho 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