3
1

More than 1 year has passed since last update.

【Nuxt.js×Firebase】ログイン状態を永続的に保持させる(リロード対策)

Last updated at Posted at 2022-01-22

#はじめに
こんにちは!
今回はログイン状態を永続的に保持させる(リロード対策)についてアウトプットしていきます!
※内容的にかなり難しいので、抽象的、間違いの部分があると思いますのでご了承ください。メモ感覚で本記事を執筆しております。

#対象
・ログイン状態を保持させたい方
・firebaseを使用してのユーザー登録、ログイン/ログアウト機能の実装を行いたい方(こちらの記事参考)

##使用環境

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

##使用ファイル,概要

ファイル名 概要
middleware/authenticated.js firebase.jsの情報から処理内容の記述。stateへ再保存。
plugins/firerbase.js 'authState'の'inject'追加。login状態の管理
store/index.js ログイン状態、ユーザー情報のstate。actions,mutationsの処理

#実装

plugins/firebase.js
  //authStateに情報が入ったら、middleware/authenticated.jsの処理が実行再開する。
  inject('authState', () => {
    //ログイン情報が入っている引数"resolve"をPromiseとしてinject,'authState'に返している。
    //authenticated.jsにて$authStateで記述可能
    return new Promise((resolve) => {
      //firebase上でログインの状態を確認(user)。ログイン状態の情報をを"resolve"に入れ引数で繋ぐ。
      firebase.auth().onAuthStateChanged((user) => {
        resolve(user || null)
      })
    })
  })

middleware/authenticated.js
export default async function ({ store, route, redirect, app }) {

    const user = await app.$authState()
    //authStateでplugins/firebase.jsファイルの処理へ非同期処理実行
    //処理が返されたら以下の処理が実行
    console.log({ user })

    if (user) {
        //store/index.jsの"getDate"に情報を入れ直す
        store.commit("getDate",
            {
                email: user.email,
            }
        )
        //上記の処理が成功したら"yesLogin"発動
        store.commit("yesLogin")
    }
    else {
        //storeからログイン情報を消す
        store.commit("noLogin")
    }
}
store/index.js
export const state = () => ({
    user: {
        email: "",
        login: false
    }
});

export const actions = {
    async confirmLogin({ commit }) {
        await this.$auth.onAuthStateChanged(function (user) {
            if (user) {
                commit("getData", {
                    email: user.email,
                });
                commit("yesLogin");
            } else {
                commit("noLogin");
            }
        });
    }
};


export const mutations = {
    getData(state, payload) {
        state.user.email = payload.email;
    },
    yesLogin(state) {
        state.user.login = true;
    },
    noLogin(state) {
        state.user.login = false;
    }
};

//firebase/userの情報を確認し、成功したら"yesLogin"、失敗したら"noLogin"が発動。

#参考記事
・Promiseについてはこちら
・async/awaitについてはこちら
・resolveについてはこちら

#まとめ
今回はログイン状態を永続的に保持させるについてアウトプットしました。

今後も引き続きQiitにポートフォリオ制作での学びをアウトプットしていきます!

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

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

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