shimotsu tech

Webフロントエンドエンジニア @ to-R inc.

【Firebase Auth】ソーシャルログインしたアカウントをすぐに削除しようとすると "auth/requires-recent-login" のエラーが出る

今作っているアプリケーションで、Firebase Authentication のソーシャルログインを活用しているものがある。

そこで、ソーシャルログインしたのち(この時点でFirebase Authentication 上にユーザー情報が作られる)、場合によってすぐにユーザー情報を削除する必要が出てきた。

しかし、ユーザー作成後すぐに同ユーザーを削除しようとすると、"auth/requires-recent-login" のエラーが出ることがわかった。

エラーの内容は、公式ドキュメントによると、以下のように書いてある。

Thrown if the user's last sign-in time does not meet the security threshold. Use firebase.User.reauthenticateWithCredential to resolve. This does not apply if the user is anonymous.

つまり、そういう重要な操作は firebase.User.reauthenticateWithCredential で再認証をしてから行ってくれ、ということらしい。

参照:

firebase.google.com

そこで、ひと手間はかかるが、以下のように一度サインインし、そこで取得した credential を用いて再認証することで、ユーザー情報削除を実行できるようにした。

  /** 会員情報削除 */
  const deleteAuth = async () => {
    try {
      // 削除には再認証が必要なのでここで実行
      firebase
        .auth()
        .signInWithPopup(provider)
        .then((result) => {
          const user = firebase.auth().currentUser

          if (!result || !result.credential) return

          user.reauthenticateWithCredential(result.credential) // credential を渡して削除を実行
            .then(async () => {
              await user.delete()
              alert("会員情報を削除しました")
            })
        })
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error)
    }
  }

これで無事ユーザー情報が削除されるようになった。