LoginSignup
3
2

More than 1 year has passed since last update.

【Nuxt.js,Firebase】ユーザー登録、ログイン実装③Googleでの登録/ログイン

Posted at

はじめに

こんにちは!
今回は前回の記事の続き、Firebase×Googleでの登録/ログインの実装についてアウトプットしていきます!

対象

・firebaseを使用してのユーザー登録、ログイン機能の実装を行いたい方
・Googleでの登録/ログインを実装したい方
前回の記事までの内容がお済みの方

使用環境

使用技術 バージョン
nuxt.js 2.15.7
firebase 9.6.1
firebase-tools 9.23.3
@nuxtjs/tailwindcss 4.2.0

使用ファイル,概要

ファイル名 概要
pages/singup 新規登録ページ
pages/login ログインページ
plugins/firerbase.js firebase導入
store/index.js ログインデータの管理&保持

firebace側の設定

firebaseの設定ででGoogleログインを実装できるようにする必要があります。
【Firebase管理画面>Authentication>Sign-in melhod】から、Google認証を有効にします。

スクリーンショット 2021-12-25 22.23.05.png

Googleユーザー登録実装

pages/singup.vue
<template>
   <button @click="googleLogin" class="h-12 w-10/12 my-4 bg-green-300">
     Googleで登録
   </button>
</template>

<script>
export default {
  methods: {
    googleLogin() {
      this.$auth
        .signInWithPopup(new this.$firebase.auth.GoogleAuthProvider())
        .then(() => {
          alert("登録に成功しました");
          this.$store.dispatch("confirmLogin");
          this.$router.push("/top");
        })
        .catch((error) => {
          console.log(error);
          alert("エラーが発生いたしました。間違い等がないか確認をし再度実施をお願いします");
        });
    },
};
</script> 

必須項目
this.$auth.signInWithPopup(new this.$firebase.auth.GoogleAuthProvider())はfirebaseでGoogleでの新規登録/ログイン機能を実装するときに使用するルールが決められている。コピペして使ってしまいしょう。

正常に登録できた時の処理(.then)
・登録完了をアラートで通知
・store/index.jsのconfirmLogin処理を呼び出し、stateにemail,passwordの情報を保持、login情報/状態をtureへ変更させる。
・登録に成功したら、強制的にTOPページへ移動させる

エラー発生時の処理(.catch)
・アラートにてメールアドレスもしくはパスワードが異なることを通知。

Googleログイン実装

pages/login.vue
<template>
  <button @click="googleLogin" class="h-12 w-10/12 my-4 bg-green-300">
    Googleでログイン
  </button>
</template>

<script>
export default {
  methods: {
    googleLogin() {
      this.$auth
        .signInWithPopup(new this.$firebase.auth.GoogleAuthProvider())
        .then(() => {
          alert("ログインに成功しました");
          this.$store.dispatch("confirmLogin");
          this.$router.push("/top");
        })
        .catch((error) => {
          console.log(error);
          alert(
            "エラーが発生いたしました。間違い等がないか確認をし再度実施をお願いします"
          );
        });
    },
 },
};

</script>

・処理内容は新規登録とログインは同じになります。

動作確認

新規登録登録

①登録画面へアクセス👉Googleで登録をクリック
スクリーンショット 2021-12-25 22.49.45.png

②登録に成功
スクリーンショット 2021-12-25 22.50.01.png

③TOPページへ強制移動
スクリーンショット 2021-12-25 22.48.50.png

ログイン

①ログイン画面へアクセス👉Googleでログインをクリック
スクリーンショット 2021-12-25 23.12.34.png

②ログインに成功
スクリーンショット 2021-12-25 22.48.25.png

③TOPページへ強制移動
スクリーンショット 2021-12-25 22.48.50.png

まとめ

今回はfirebase×Google登録/ログインの実装について記事にしました。次回に、
・ログアウト時の処理

についてQiitにまとめていきます!

今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。

最後までご愛読ありがとうございました!

3
2
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
3
2