坂本研のゼミ室

Vue.js + Firebaseで観光地の口コミサイトを作る -1-

今回はVue.jsとFirebaseを使って、認証機能までやっていく。


Firebase

Firebaseとは、Googleが提供しているWebアプリ・モバイルアプリのバックエンドサービスです。
mBaasに位置付けされ数多くの機能が用意してあります。
Firebase を使うことで、開発者はバックエンドで動くサービスを作成・管理する必要がなくなります。
firebase.google.com

Vueプロジェクトの作成

  • npmを使ってvue-cliをインストールする
npm install -g @vue/cli
  • GUIで作っていく
vue ui

http://localhost:8000にアクセスすると画面が出てくるので、
プロジェクトを作成したいディレクトリを選択 → 「新しいプロジェクトを作成」
今回は、「miyazaki-tours」というプロジェクトを作成しました

  • パッケージをインストール

依存 → 依存をインストール
vue上でページ遷移を行うための「vue-router」、
firebaseの機能を使うために「firebase」パッケージのインストールを行う
f:id:TakaShinoda:20190721005714p:plain
f:id:TakaShinoda:20190721005734p:plain


  • ブラウザで確認

開発中のアプリケーションの確認方法
タスク → serve → タスクの実行
http://localhost:8080にアクセスするとvueのアプリケーションが表示される


vue-routerによるページ遷移の作成

  • アプリのメインとなるページを作成

miyazaki-tours/src/components/Tours.vue

<template>
  <div id="tours">
      <h2>観光スポット</h2>
  </div>
</template>
 
<style>
</style>

  • アカウント作成 (サインアップ) ページ作成

miyazaki-tours/src/components/Signup.vue

<template>
  <div id="Singup">
    <h2>サインアップ</h2>
  </div>
</template>

<style>
</style>
  • ログイン (サインイン) ページ作成

miyazaki-tours/src/components/Signup.vue

<template>
  <div id="Singin">
    <h2>サインイン</h2>
  </div>
</template>

<style>
</style>
  • vue-routerの設定を行うrouter.jsを新規作成

miyazaki-tours/src/router.js

import Vue from 'vue'
import Router from 'vue-router'
import Tours from '@/components/Tours.vue'
import Signup from '@/components/Signup'
import Signin from '@/components/Signin'

Vue.use(Router)
 
let router =  new Router({
  mode: 'history',
  routes: [
    {
        path: '/',
        name: 'tours',
        component: Tours,
    },
    {
        path: '/signup',
        name: 'Signup',
        component: Signup,
    },
    {
        path: '/signin',
        name: 'Signin',
        component: Signin,
    },
  ]
})

export default router
  • main.jsの編集

miyazaki-tours/src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false


new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
  • App.vueの編集

miyazaki-tours/src/App.vue

<template>
  <div id="app">
    <h1>観光掲示板</h1>
    <router-view/>
  </div>
</template>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Firebaseでプロジェクトを作成

  • GoogleアカウントでFirebaseにログイン
  • 「プロジェクトを追加」をクリック

f:id:TakaShinoda:20190721020612p:plain

  • プロジェクト名を入力し、プロジェクトを作成

f:id:TakaShinoda:20190721021001p:plain

  • 表示された情報をコピーする

f:id:TakaShinoda:20190721021201p:plain

  • main.jsの編集

miyazaki-tours/src/main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import firebase from 'firebase' 

Vue.config.productionTip = false

//firebase
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: ""
};
firebase.initializeApp(firebaseConfig);


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

メール / パスワードによる認証

  • Firebaseで「メール / パスワード」認証を有効化する

左メニュー「Authentication」選択
ログイン方法から「メール/パスワード」を有効化
f:id:TakaShinoda:20190721022240p:plain

  • アカウント作成 (サインアップ) ページの編集

miyazaki-tours/src/components/Signup.vue

<template>
  <div id="Singup">
    <h2>サインアップ</h2>
    <!--登録フォーム-->
    <input type="email" placeholder="email" v-model="email">
    <input type="password" placeholder="password" v-model="password">
    <button v-on:click="signUp">登録</button>

    <!-- サインインへの遷移ボタン -->
    <p>アカウントをすでにお持ちの方
      <router-link to="/signin">sign in now</router-link>
    </p>
  </div>
</template>

<script>
import firebase from 'firebase';

export default {
  name: "Singup",
  data() {
    return {
      email: "",
      password: "",
    };
  },
  methods: {
    signUp: function() {
      firebase
        .auth()
        .createUserWithEmailAndPassword(
          this.email,
          this.password
        )
        .then(user => {
          // 成功時
          alert("Create account: " + user.user.email);
        })
        .catch(error => {
          // 失敗時
          alert(error.message);
        });
    }
  }
};
</script>
 
<style>
</style>
  • 新しいユーザーのメールアドレスとパスワードを 「createUserWithEmailAndPassword」に渡して、新しいアカウントを作成する
firebase.auth().createUserWithEmailAndPassword()
  • 実際に新規登録をやってみる

f:id:TakaShinoda:20190721100215p:plain
登録に成功するとfirebaseのコンソールからユーザを確認できる
f:id:TakaShinoda:20190721100230p:plain


  • ログイン (サインイン) ページの編集

miyazaki-tours/src/components/Signup.vue

<template>
  <div id="signin">
    <h2>サインイン</h2>
    <!-- emailとpasswordの入力欄 -->
    <input type="email" placeholder="email" v-model="email">
    <input type="password" placeholder="Password" v-model="password">
    <button v-on:click="signIn">Signin</button>

    <!-- サインアップページ遷移ボタン -->
    <p>
      アカウントをお持ちではない方
      <router-link to="/signup">新規作成</router-link>
    </p>
  </div>
</template>

<script>
import firebase from "firebase"; 

export default {
  name: "Signin",
  data() {
    return {
      email: "",
      password: ""
    };
  },
  methods: {
    // signinボタンを押したときに実行されるfunction
    signIn: function() {
      firebase
        .auth()
        .signInWithEmailAndPassword(this.email, this.password)
        .then(user => {
          // ログインが成功した場合にメインページに遷移させる
          alert("success : " + user.user.email);
          this.$router.push("/");
        })
        .catch(error => {
          // ログインに失敗した場合
          alert(error.message);
        });
    }
  }
};
</script>


<style>
</style>
  • firebaseの「signInWithEmailAndPassword」メソッドで簡単にユーザのログインを実装することができる
signInWithEmailAndPassword()

f:id:TakaShinoda:20190721101230p:plain


  • ログアウトページ作成

「signOut」メソッドでログアウトを実装することができる
miyazaki-tours/src/components/Signout.vue

<template>
  <div id="Singout">
    <h2>ログアウト</h2>
    <!--ログアウトボタン-->
    <button v-on:click="signOut">ログアウト</button>

  </div>
</template>

<script>
import firebase from 'firebase';

export default {
  name: "Singout",

  methods: {
    signOut: function() {
        firebase
        .auth()
        .signOut()
        .then(user => {
          // 成功時
          alert("Signout account");
          this.$router.push("/signin");
        })
        .catch(error => {
          // 失敗時
          alert(error.message);
        });
    }
  }
};
</script>
 
<style>
</style>

f:id:TakaShinoda:20190721144110p:plain


まとめ

これで認証機能の実装はできました。
今回は、メール / パスワードでの認証でしたが、Firebaseは他にも多くの機能があるので今後対応できるようにしていきたいと考えます。
次回は、メインとなる機能を実装していきたいと思います。