在 Firebase 中管理使用者

新增使用者

如要在 Firebase 專案中建立新使用者,請呼叫 createUser 方法,或使用聯合身分識別提供者 (例如 Google 登入Facebook 登入) 首次登入使用者。

您也可以在「使用者」頁面,透過 Firebase 控制台的「驗證」部分建立新的密碼驗證使用者。

取得目前登入的使用者

建議您在驗證物件上設定事件監聽器,藉此取得目前使用者:

Swift

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

Objective-C

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

使用事件監聽器可確保您取得目前使用者時,驗證物件不會處於中繼狀態 (例如初始化)。

您也可以使用 currentUser 屬性取得目前登入的使用者。如果使用者未登入,currentUser 會是 nil:

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.
  // ...
}

取得使用者個人資料

如要取得使用者的個人資料資訊,請使用 FIRUser 執行個體的屬性。例如:

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

取得使用者的特定供應商個人資料資訊

如要取得從連結至使用者的登入服務供應商擷取的個人資料資訊,請使用 providerData 屬性。例如:

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

更新使用者個人資料

您可以使用 UserProfileChangeRequest 類別更新使用者的基本個人資料資訊,包括使用者的顯示名稱和個人資料相片網址。例如:

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) {
  // ...
}];

設定使用者的電子郵件地址

您可以使用 updateEmail 方法設定使用者的電子郵件地址。例如:

Swift

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

Objective-C

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

傳送驗證電子郵件給使用者

您可以使用 sendEmailVerificationWithCompletion: 方法,傳送地址驗證電子郵件給使用者。例如:

Swift

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

Objective-C

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

您可以在Firebase控制台的「驗證」部分,自訂「電子郵件範本」頁面中使用的電子郵件範本。請參閱 Firebase 說明中心的「電子郵件範本」。

您也可以透過延續網址傳遞狀態,在傳送驗證電子郵件時重新導向回應用程式。

此外,您也可以在傳送電子郵件前,更新 Auth 執行個體上的語言代碼,將驗證電子郵件本地化。例如:

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

設定使用者密碼

您可以使用 updatePassword 方法設定使用者密碼。例如:

Swift

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

Objective-C

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

傳送密碼重設電子郵件

您可以使用 sendPasswordReset 方法,傳送重設密碼電子郵件給使用者。例如:

Swift

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

Objective-C

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

您可以在Firebase控制台的「驗證」部分,自訂「電子郵件範本」頁面中使用的電子郵件範本。請參閱 Firebase 說明中心的「電子郵件範本」。

您也可以透過「延續網址」傳遞狀態,在傳送重設密碼電子郵件時重新導向回應用程式。

此外,您也可以在傳送電子郵件前,更新驗證執行個體上的語言代碼,將重設密碼電子郵件本地化。例如:

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

您也可以從 Firebase 控制台傳送重設密碼電子郵件。

刪除使用者

您可以使用 delete 方法刪除使用者帳戶。例如:

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

您也可以前往 Firebase 控制台的「驗證」專區,在「使用者」頁面中刪除使用者。

重新驗證使用者

執行部分安全性敏感操作 (例如刪除帳戶設定主要電子郵件地址變更密碼) 時,使用者必須最近登入帳戶。如果您執行上述任一動作,且使用者登入時間過長,動作就會失敗並顯示 FIRAuthErrorCodeCredentialTooOld 錯誤。發生這種情況時,請向使用者索取新的登入憑證,並將憑證傳遞至 reauthenticate,重新驗證使用者。例如:

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

匯入使用者帳戶

您可以使用 Firebase CLI 的 auth:import 指令,將檔案中的使用者帳戶匯入 Firebase 專案。例如:

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