dayjournal memo

Total 975 articles!!

Try #025 – FirebaseとVue.jsでログイン機能を構築してみた

Yasunori Kirimoto's avatar

画像


画像




画像




FirebaseとVue.jsでログイン機能を構築してみました!



事前準備


全体の構成はできるだけシンプルに。

バックエンド - ユーザー管理

  • Firebase

フロントエンド - ログイン機能

  • Vue.js


バックエンド


まずは、バックエンドを構築していきます。基本的にはコンソール設定のみで構築終わります!


はじめに、下記アイコンをクリックします。 画像


任意の名称でアプリを作成します。 画像


アプリが作成されると、Firebaseを利用するための設定が表示されるのでコピーしておきます。 画像


ユーザーの認証をするために、Authenticationをクリック 画像


ユーザー認証方法を設定します。 画像


今回は、メールアドレスとパスワードで設定します。 画像


ユーザーを追加ボタンをクリックします。 画像


仮に1ユーザーを追加してみます。 画像


これでバックエンドの構築は完了になります。



フロントエンド


次に、フロントエンドを構築していきます。


実行環境

node v12.7.0
npm v6.10.0


はじめに、Firebaseの環境をインストールします。

npm install firebase

画像



あとは、実際にログイン機能のコードを記述していきます。


全体構成

画像


package.json

{
  "name": "firebase_prj",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "bootstrap-vue": "^2.0.0-rc.19",
    "core-js": "^2.6.5",
    "firebase": "^6.3.5",
    "vue": "^2.6.10",
    "vue-router": "^3.0.3",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@babel/polyfill": "^7.4.4",
    "@vue/cli-plugin-babel": "^3.8.0",
    "@vue/cli-plugin-eslint": "^3.8.0",
    "@vue/cli-service": "^3.8.0",
    "babel-eslint": "^10.0.1",
    "bootstrap": "^4.3.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "mutationobserver-shim": "^0.3.3",
    "node-sass": "^4.12.0",
    "popper.js": "^1.15.0",
    "portal-vue": "^2.1.4",
    "sass-loader": "^7.1.0",
    "vue-cli-plugin-bootstrap-vue": "^0.4.0",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}


/src


main.js

import '@babel/polyfill'
import 'mutationobserver-shim'
import Vue from 'vue'
import './plugins/bootstrap-vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Firebase読み込み
import firebase from 'firebase'

Vue.config.productionTip = false

// Firebase設定
let firebaseConfig = {
    apiKey: "xxxxxxxxxx",
    authDomain: "sample-1908.firebaseapp.com",
    databaseURL: "https://sample-1908.firebaseio.com",
    projectId: "sample-1908",
    storageBucket: "",
    messagingSenderId: "xxxxxxxxxx",
    appId: "xxxxxxxxxx"
};
firebase.initializeApp(firebaseConfig);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')


router.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

// Firebase読み込み
import firebase from 'firebase'

Vue.use(Router)

let router = new Router({
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home
        },
        {
            path: '/about',
            name: 'about',
            component: About,
            meta: { requiresAuth: true }
        }
    ]
});

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
    if (requiresAuth) {
        //サインインの有無判断
        firebase.auth().onAuthStateChanged(function (user) {
            if (user) {
                next()
            } else {
                next({
                    path: '/'
                })
            }
        })
    } else {
        next()
    }
});

export default router


src/views


About.vue

<template>
    <div class='about'>
        <!--題名-->
        <h1 class='mt-5'>
            ログイン済
        </h1>

        <!--サインアウトボタン-->
        <button
            @click='signOut'
            class='btn btn-primary mt-5'
        >SignOut</button>
    </div>
</template>

<script>
    // Firebase読み込み
    import firebase from 'firebase'

    export default {
        name: 'about',
        methods: {
            signOut: function () {
                //サインアウト処理
                firebase.auth().signOut();
                console.log('signOut!');
            }
        }
    }
</script>


Home.vue

<template>
    <div class='home'>
        <b-form-group class='mt-5'>
            <b-row>
                <b-col cols='2' offset-sm='5'  class='mt-3'>
                    <!--ユーザー名-->
                    <b-form-input
                        type='text'
                        placeholder='Username'
                        v-model='username'
                    ></b-form-input>
                </b-col>
                <b-col cols='2' offset-sm='5'  class='mt-3'>
                    <!--パスワード-->
                    <b-form-input
                        type='password'
                        placeholder='Password'
                        v-model='password'
                    ></b-form-input>
                </b-col>
            </b-row>
        </b-form-group>

        <!--サインインボタン-->
        <button
            @click='signIn'
            class='btn btn-primary mt-3'
        >SignIn</button>
    </div>
</template>

<script>
    // Firebase読み込み
    import firebase from 'firebase'

    export default {
        name: 'home',
        methods: {
            signIn: function () {
                //サインイン処理
                firebase.auth().signInWithEmailAndPassword(this.username, this.password).then(
                    user => {
                        console.log('Success!');
                        this.$router.push('/about')
                    },
                    err => {
                        alert(err.message)
                    }
                )
            }
        },
        data() {
            return {
                username: '',
                password: ''
            }
        }
    }
</script>


簡易ローカルサーバーで確認

npm run serve


ローカルサーバーを立ち上げて、ログインしてみます。

画像




FirebaseとVue.jsを利用することで、手軽にログイン機能の構築ができました!

前回紹介した「Amplify」と、今回の「Firebase」どちらもサーバーレスで手軽にログイン機能を構築することが可能になります。

個人的にはサクッとサービスを構築する場合は、コンソールがわかりやすい「Firebase」でまずは構築するのがいいのかもしれません。「Amplify」もかなり使いやすくなったのでおすすめです!

FirebaseとAmplify、それぞれでメリット・デメリットがあるので目的に応じて選択する必要がありそうです。



Vue.jsについて、他にも記事を書いています。よろしければぜひ。
tags - Vue.js



book

Q&A