Firebase (4) - Email/Password Authentication -


Firebase Typescript React

Firebase Authenticationを使ってメールアドレスとパスワードによるログインおよび新規アカウント登録のAPIを利用してみた。

前回からの変更点としてGoogleLogin.tsxでレンダリングしてたのを変えたくらいであとはほぼ変わらないので省略。

Firebaseの設定

Firebaseコンソールから「サインイン メソッド」タブを開き、ログイン プロバイダーとして「メール/パスワード」を有効にしておく。

src/components/SignForm.tsx

前回はGoogleLogin.tsxっていうコンポーネントを描画していたが今回はこっちを使用する。メールアドレスとパスワードでのログイン処理および新規アカウント登録を行うコンポーネント。

import { createUserWithEmailAndPassword, sendEmailVerification, signInWithEmailAndPassword } from 'firebase/auth';
import { useCallback, useRef } from 'react';
import { auth } from '../lib/firebase';

const SignForm = (): React.JSX.Element => {
  const emailRef = useRef<HTMLInputElement>(null);
  const passwordRef = useRef<HTMLInputElement>(null);

  const handleLoginClick = useCallback(async () => {
    const email    = emailRef.current?.value ?? '';
    const password = passwordRef.current?.value ?? '';
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    // userCredential.userからログインしたユーザー情報を取りそれを元にユーザーテーブルとかに入れるなり
  }, []);

  const handleSignUpClick = useCallback(async () => {
    const email    = emailRef.current?.value ?? '';
    const password = passwordRef.current?.value ?? '';
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);

    if (userCredential.user) {
      await sendEmailVerification(userCredential.user);
    }
  }, []);

  return (
    <div className="auth-form">
      <h3>ログイン/登録</h3>
      <input type="email" ref={emailRef} placeholder="メールアドレス" />
      <input type="password" ref={passwordRef} placeholder="パスワード(6文字以上)" />
      <button type="button" onClick={handleLoginClick}>ログイン</button>
      <button type="button" onClick={handleSignUpClick} style={{ backgroundColor: '#28a745' }}>新規アカウント登録</button>
    </div>
  );
};

export default SignForm;

既存ユーザーのログインにはsignInWithEmailAndPassword、新規ユーザーの登録にはcreateUserWithEmailAndPasswordを使用。
また、新規アカウント登録が成功した際にはsendEmailVerificationで登録されたメールアドレス宛にFirebaseから自動的に本登録確認メールが送信される。ちなみに以下のようにsendEmailVerificationの引数にオプション(ActionCodeSettings)をつけることでメール認証が承認されたあとにリダイレクトしてくれるようにすることも可能

await sendEmailVerification(
  userCredential.user,
  {
    url: `https://example.com/user/create`,
    handleCodeInApp: true
  }
);

というような感じでメールアドレス・パスワードでの新規アカウントの登録・ログインなどもFirebase Authentication APIで作れちゃうよってことで

ちなみに今回はやらなかったけどパスワードをリセットさせるAPI(sendPasswordResetEmail)などもあるので(ry

余談

メール認証が承認されたかをチェックするには

if (!currentUser.emailVerified) {
  return <div>Not Verified!</div>;
}

というようにemailVerifiedというプロパティでチェックできるのでそれを利用する

余談2

ちなみにsendSignInLinkToEmailっていうのを使うとメールでリンクが送られてきてそのリンクでログインできるような機能も作れるみたい
ただし、これを使うには上記で書いたActionCodeSettingsのようなオプション指定が必須だそうで

Table of Contents
Firebaseの設定 src/components/SignForm.tsx 余談 メール認証が承認されたかをチェックするには 余談2
関連記事