LoginSignup
9
5

More than 1 year has passed since last update.

【Swift5】Firebase Authでメールの重複チェックを行う

Posted at

背景

Firebaseでメールの重複チェックを行う時に、Firestoreのuserデータから検索を行う手段が多かったので
Firebase Authのみで重複チェックを行う方法を記載しようと思いました。

実装

import Firebase

func checkEmailExist(email: String, completion: @escaping ((Result<Bool, Error>) -> Void) {
  // SignInの方法を取得するメソッドを使用
  Auth.auth().fetchSignInMethods(forEmail: email, completion: { (method, error) in
    if let err = error {
      completion(.failure(err))
      return
    }
    // すでにメールアドレスの認証などされている場合は
    // methodの中に"EmailLink"や"Email"などの認証方法が入る
    guard let method = method, !method.isEmpty else {
      // 何もない場合は存在しない
      completion(.success(false))
      return
    }

    // methodに認証方法が入っている場合は存在する判定
    completion(.success(true))
  })
}

上記のメソッドをメールアドレスを入力しているViewControllerなどから呼び出してあげれば良いです!
Result型がわからない場合に備えて、ViewControllerでの実装例も載せておきます。

実装例

import UIKit

class SampleViewController: UIViewController {
  @IBOutlet var textField: UITextField!

  override func viewDidLoad() {
    super.viewDidLoad()
  }

  @IBAction func tapButton(_ sender: Any) {
     guard let email = textField.text else {
       return
     }

     checkEmailExist(email: email, completion: { result in
       switch result {
         case let .success(isExist):
           if (isExist) {
             // メールアドレスが重複した時の処理
           } else {
             // メールアドレスが重複していないので、認証処理を行う
           }
         case let .failure(error):
           // エラー時のハンドリング(ダイアログ出したり) 
       }
     })
  }
}

他の実装方法について

FirestoreのDB構造
Users
  - ユーザーA
    - hogehoge1@sss.com
  - ユーザーB
    - hogehoge2@sss.com

上記のようにFirestoreのUsersコレクションを作成してメールアドレスで検索する方法もありますが、
セキュリティ的にメールアドレスを全てのユーザーが見れる状態はあまり良い状態ではない(そういうアプリであれば良いですが)
と思うので、こちらの方法はあまり推奨できないと思います。

良いFirebaseライフを!

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5