LoginSignup
28
32

More than 3 years have passed since last update.

Firebase Authenticationのemail, passowrd認証まわりのメモ

Last updated at Posted at 2019-12-27

email, password認証はよく使うのでメモ。

前提

  • asyncの中で利用すること想定(そのコード割愛)

既にemailが登録されているかどうか

専用の関数が欲しいところですが、内容です。
いくつか方法があるようですが、下記のように確認できるようです。

const providers = await firebase.auth().fetchSignInMethodsForEmail(email);
if (providers.findIndex(p => p === firebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD) !== -1) {
    console.log("登録されています");
    return;
}

fetchSignInMethodsForEmail()を実行すると、既にemail-passowrd認証でemailが登録されている場合は["password"]といった形で、既に利用済の認証名が配列で返るようです。なので配列中に"password"が含まれているかどうかをfindIndex()で確認し、含まれてない場合-1が変えるので、-1以外なら"password"が含まれる=登録済みということになります。

なお、認証名はfirebase.auth.EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHODで取れるようなのでそれを利用しています。

ユーザーの作成

ユーザーの作成。作成されたユーザーはres.userで取得可能。

const res = await firebase.auth().signInWithEmailAndPassword(email, password);
console.log(res.user.uid);

ログイン

ログイン(SignIn)。ログインしたユーザーはres.userで取得可能。

const res = await firebase.auth().signInWithEmailAndPassword(email, password);
console.log(res.user.uid);

Email確認メールの送信

Firebase Authの仕様では事前にemail確認(のメールを送ったり)しません。
確認が必要な場合はユーザー作成後に行いことになります。

//ユーザーを取得(signInとかなんでもいい)
const res = await firebase.auth().createUserWithEmailAndPassword(email, password);

//確認メール送付
res.user.sendEmailVerification({
    url: 'http://www.eizaburo.com',
    handleCodeInApp: false,
});

Email確認済の確認

Emailの確認が終わった状態かどうかは下記の方法で確認できます。

//ログイン
const res = await firebase.auth().signInWithEmailAndPassword(email, password);
//状態チェック
if (res.user.emailVerified) {
    console.log("Email認証完了");
} else {
    console.log("Email認証未完了");
}

パスワードリセットメールの送信

パスワードのリセットはログイン不要(当然ですが)でemailさえわかれば送信可能です。

await firebase.auth().sendPasswordResetEmail(email,{
    url: 'http://www.eizaburo.com',
    handleCodeInApp: false,
});

その他

  • email変更処理もできるが、あまり使わないので割愛。
  • 何もしなければFirebaseが用意したページとなるが、カスタマイズも可能

参考

28
32
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
28
32