【Firebase】Googleログインを実装する【Vuex】

前書き

melheaven.hatenadiary.jp

前回メール認証のログイン機能を実装しました。
この時はポートフォーリオの開発でログインするのは自分くらいだったので、メール認証でも「まあいいか」と思っていました。
今回製作しているアプリケーションは誰でも気楽にログインしてほしいので、Googleログイン機能を実装しました。

実装(main.js)

firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)

main.jsにてsetPersistenceを設定することで、リロードしても、ログイン状態を確保できます。

gurutaka-log.com

実装(store/session.js)

Authentication処理はVuexのStore機能を活用しておくと、
VueプロジェクトのあらゆるVueファイルからログイン情報を簡単に抜き取ることができます。

state

ログイン情報(=user)とログイン状態(=status)を設定します。

const state = {
    user: {},
    status: false,
}

getters

Vueファイルからstate情報を抜く出す時にgettersを経由します。

const getters = {
    user(state) {
        return state.user;
    },
    isSignedIn(state) {
        return state.status;
    }
}

mutations

actionからstate情報を更新するときにmutationsを呼び出します。

const mutations = {
    onAuthStateChanged(state, user) {
        state.user = user;
    },
    onUserStatusChanged(state, status) {
        state.status = status;
    },
}

actions

actionsにLogin処理、Logput処理、OnAuth処理を実行します。
以下ではそれぞれの処理を記載していきます。

const actions = {
    login({ commit }) {
        const provider = new firebase.auth.GoogleAuthProvider();
        firebase.auth().signInWithPopup(provider).then(function (result) {
            // commit('onUserStatusChanged', result.user.uid ? true : false);
            // commit('onAuthStateChanged', result.user);
            router.push('/')
        }).catch(() => alert('ログインに失敗しました'));
    },
// → 続き:logout

ログイン処理ではfirebase.authからGoogleAuthProvider()を呼び出します。
さらにsignInWithPopupを呼び出し、ログイン認証を行います。
ここではページ遷移、ユーザーの情報を取得して処理を行うなどの処理を書くといいらしいです。

    logout({ commit }) {
        firebase.auth().signOut().then(() => {
             // commit('onAuthStateChanged', null);
             // commit('onUserStatusChanged', false);
        })
    },
// → 続き:onAuth

ログアウト処理ではstoreのstateに格納されたユーザー情報を削除し、
ログイン状態をfalseにを更新します。

    onAuth({ commit }) {
        firebase.auth().onAuthStateChanged(user => {
            user = user ? user : {};
            commit('onAuthStateChanged', user);
            commit('onUserStatusChanged', user.uid ? true : false);
        });
    },
}

onAuth処理はVueファイルcreated()などで仮想DOMが作成された時に、
ログイン情報と状態を取得し、storeのstateに情報を格納します。
現在のログイン情報を抜き出して、ログインしている時の処理 or していない時の処理を記述します。

App.vueのcreatedに記述して、リロードしてもログイン情報を保持できるようにしました。

実装(Vueファイルのログインページ)

ログインページにはGoogle認証を可能にするボタンが必要になります。
ログインボタンを押すとGoogleのアカウント認証に移動し、認証後アプリケーションに帰ってきて、
ログインが実現できています。

<button type="button" class="google-button" @click="doLogin">
          <span class="google-button__icon">
            <svg viewBox="0 0 366 372" xmlns="http://www.w3.org/2000/svg">
              <path
                d="M125.9 10.2c40.2-13.9 85.3-13.6 125.3 1.1 22.2 8.2 42.5 21 59.9 37.1-5.8 6.3-12.1 12.2-18.1 18.3l-34.2 34.2c-11.3-10.8-25.1-19-40.1-23.6-17.6-5.3-36.6-6.1-54.6-2.2-21 4.5-40.5 15.5-55.6 30.9-12.2 12.3-21.4 27.5-27 43.9-20.3-15.8-40.6-31.5-61-47.3 21.5-43 60.1-76.9 105.4-92.4z"
                id="Shape"
                fill="#EA4335"
              />
              <path
                d="M20.6 102.4c20.3 15.8 40.6 31.5 61 47.3-8 23.3-8 49.2 0 72.4-20.3 15.8-40.6 31.6-60.9 47.3C1.9 232.7-3.8 189.6 4.4 149.2c3.3-16.2 8.7-32 16.2-46.8z"
                id="Shape"
                fill="#FBBC05"
              />
              <path
                d="M361.7 151.1c5.8 32.7 4.5 66.8-4.7 98.8-8.5 29.3-24.6 56.5-47.1 77.2l-59.1-45.9c19.5-13.1 33.3-34.3 37.2-57.5H186.6c.1-24.2.1-48.4.1-72.6h175z"
                id="Shape"
                fill="#4285F4"
              />
              <path
                d="M81.4 222.2c7.8 22.9 22.8 43.2 42.6 57.1 12.4 8.7 26.6 14.9 41.4 17.9 14.6 3 29.7 2.6 44.4.1 14.6-2.6 28.7-7.9 41-16.2l59.1 45.9c-21.3 19.7-48 33.1-76.2 39.6-31.2 7.1-64.2 7.3-95.2-1-24.6-6.5-47.7-18.2-67.6-34.1-20.9-16.6-38.3-38-50.4-62 20.3-15.7 40.6-31.5 60.9-47.3z"
                fill="#34A853"
              />
            </svg>
          </span>
          <span class="google-button__text">Sign in with Google</span>
        </button>
  methods: {
    doLogin() {
      this.$store.dispatch("login");
    }

結果

f:id:electric-city:20201216085326p:plain
ログイン画面

参考

qiita.com