LoginSignup
0
0

More than 3 years have passed since last update.

Nuxt.js+Firebaseでログイン情報を保持したい

Last updated at Posted at 2020-05-20

Nuxt.js+Firebaseの勉強を始めたばかりです。
みなさんの記事を見よう見まねで、Googleアカウントでのログイン認証ができるWebページを作成しました。

やりたいこと

ログイン後に、ログイン画面 https://xxx.firebaseapp.com/login/ に遷移したところ、画面が真っ白になりました。ログイン情報を保存して、ログインしていればリダイレクトするようにしたいです。

環境

  • 開発環境 WindowsPC
  • node 12.13.0
  • npm 6.12.0
  • npx 6.12.0
  • Firebase 7.3.0
  • Vue CLI 4.0.5
  • Nuxt.js 2.10.2

リダイレクト処理+ログイン情報の保持

  • ~/pages
    • login.vue
  • ~/middleware
    • notAuthenticated.js
  • ~/store
    • auth.js

ログイン画面 login.vue のmiddlewareにリダイレクト処理を含むミドルウェア notAuthenticated を追加しました。

pages/login.vue
<template>
  <div>
    <FirebaseAuth/>
  </div>
</template>

<script>
import FirebaseAuth from '@/components/FirebaseAuth.vue';
import { mapState, mapGetters, mapActions } from "vuex";

export default {
  middleware: 'notAuthenticated',
  name: 'Login',
  components: {
    FirebaseAuth
  }
}
</script>

リダイレクト処理を含むミドルウェア notAuthenticated は次のようにしました。

middleware/notAuthenticated.js
export default function ({ store, redirect }) {  
  if (store.getters["auth/isLoggedIn"]) {
    return redirect('/');
  }
}

これでログイン画面にアクセスした時に、ミドルウェアで認証情報の有無をチェックし、適切なページへリダイレクトしてくれます。
補足ですが、ミドルウェアの実行順序は以下の順とのこと。

  1. nuxt.config.js
  2. Layout Middleware
  3. Page Middleware

続いて、ログイン情報を保持するための処理です。

store/auth.js
import Vue from 'vue';
import { auth } from '~/plugins/firebase';

export const state = () => ({
        user: {},
        status: ""
    });

export const mutations = {
        setUser(state, user) {
            state.status = "loggedIn";
            state.user = user;
        },
        logout(state) {
            state.status = "loggedOut";
            state.user = {};
        }
    };

export const getters = {
        isLoggedIn: (state) => {
          return state.status === "loggedIn";
        },
        getUsername: (state) => state.user.displayName
    };

export const actions = {
        gotUser({ commit }, user) {
            commit("setUser", user);
        },
        logout({ commit }) {
            auth.signOut().then(() => {
                commit("logout");
            })
        },
    };

このコードを書くだけでは state.status の値は保存されません。
リロード・画面遷移でデータが消えてしまうので、vuex-persistedstateを試すことにしました。

vuex-persistedstate

まずはインストールします。コマンドは npm install vuex-persistedstate --save です。

  • ~/plugins
    • persistedstate.js
  • ~/store
    • index.js
  • ~/nuxt.config.js
plugins/persistedstate.js
export default async (context) => {
  await context.store.dispatch("nuxtClientInit", context);
};
store/index.js
import { vuexfireMutations } from 'vuexfire';
import createPersistedState from "vuex-persistedstate";

export const mutations = {
  ...vuexfireMutations
};

export const actions = {
  nuxtClientInit ({ commit, state, dispatch }, { req }) {
    createPersistedState()(this);
  },
};
nuxt.config.js
  plugins: [
    '~/plugins/firebase',
    { src: "~plugins/persistedstate.js", ssr: false },
  ],
0
0
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
0
0