kakakakakku blog

Weekly Tech Blog: Keep on Learning!

Firebase Authentication で「メール認証」と「Google 認証」を実装できる無料コース「Vue.js + Firebase Authentication」を受講した

2週間前に Vue School が公開している無料コース「Vue.js + Firebase Realtime Database」を受講して,まとめ記事を書いたけど,先週に新しく無料コース「Vue.js + Firebase Authentication」が公開されたので,さっそく受講してみた.一番最後に Firebase Realtime Database を使う箇所があるので,順番的には「Vue.js + Firebase Realtime Database」を受講してから「Vue.js + Firebase Authentication」を受講すると良いと思う.今回も Vue.js 初学者と Firebase Authentication 初学者にオススメのコースだった.

kakakakakku.hatenablog.com

Vue.js + Firebase Authentication

vueschool.io

コースは計9個の動画で構成されている(そのうち1個はまだ非公開になっている).特に Firebase Authentication を使って「メール認証」と「Google 認証」が簡単に実装できる点が素晴らしく,こんなに簡単にできちゃって良いのだろうか?と思うほどだった.

  • Introduction to Firebase Authentication ⏲ 1:35
  • Sign up, in, or out with Firebase Authentication ⏲ 7:48
  • Firebase Authentication Error Handling ⏲ 3:17
  • Firebase Authentication via Third-Party Providers ⏲ 3:37
  • Update Firebase Authentication User Profile ⏲ 2:59
  • Update Firebase Authentication User Email and Password ⏲ 3:28
  • Link Multiple Firebase Authentication Providers to One User Account ⏲ 5:19
  • Additional User Data and Firebase Authentication ⏲ 4:19
  • Protected Routes with Vue Router, Firebase Authentication and Vuex ⏲ Coming Soon !

なお,以下のように英語字幕が出るので,英語が苦手な人でも,問題なく受講できると思う.前回と少し UI が変わっていて,再生速度の変更などの機能が追加されていた.

f:id:kakku22:20180522144639p:plain

(受講画面例)

実装した認証アプリケーション

以下の認証アプリケーションを実装した.

  • 「メール認証」と「Google 認証」でサインイン/サインアウトができる
  • 「メール認証」から「Google 認証」に紐付けることができる
  • プロフィールを更新することができる
  • パスワードの更新することができる
  • 追加情報(今回は好きな食べ物)を Firebase Realtime Database に登録することができる

f:id:kakku22:20180522144739p:plain

(実装した認証アプリケーションの画面)

前提

今回は localhostindex.html の動作確認ができるようにする必要があり,動画の中では特に紹介はなかったけど,今回は local-web-server を使うことにした.他のツールでも問題ないと思う.local-web-server を使うと http://localhost:8000 で動作確認ができるようになる.

$ npm install -g local-web-server
$ ws --spa index.html

www.npmjs.com

Introduction to Firebase Authentication

Sign up, in, or out with Firebase Authentication

まず,サポートされている認証方式の多さに驚いた.メールだけではなく,Google / Facebook / Twitter / GitHub などがあった.また,今回のコースでは使わなかったけど「匿名認証」もサポートされていて,あると便利な場合もありそう.なお,実行する前に「承認済みドメイン」を確認しておく必要がある.デフォルトで localhost は承認されているので,今回は localhost で動作確認をすることにした.

f:id:kakku22:20180522145250p:plain

(サポートしている認証方式一覧)

そして今回も実装は GitHub に公開されている.ただし,master ブランチだと完成形の index.html になっているので,写経しながら進める場合は,コミット履歴から1番最初に戻す必要がある.

$ git checkout e82855604d8374ae45b824e47d3a50f7fe5066ea index.html

残念ながら,今回は最初のコミットでも,微妙に実装が進んでしまっているので,正確に写経するのであれば index.html を以下の雛形にすると良いかと.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Firebase Authentication</title>
</head>
<body>

<div id="app">
  <h1>Vue School - Firebase Authentication</h1>
</div>

</body>
</html>

実装に入る前に,Chrome DevTools のコンソールから「メール認証」を試した.あまりにも簡単で驚いた.

firebase.auth().createUserWithEmailAndPassword('1@example.com', '12345678')

うまく動いたので,次は Vue.js でフォームとメソッドを実装した.簡単に「メール認証」を実現できた.

methods: {
  register () {
    firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
  },
  signOut () {
    firebase.auth().signOut()
  },
  signIn () {
    firebase.auth().signInWithEmailAndPassword(this.email, this.password)
  }
}

f:id:kakku22:20180522145329p:plain

(実装したフォーム)

f:id:kakku22:20180522145355p:plain

(認証後の Firebase Authentication コンソール)

Firebase Authentication Error Handling

現状だと,パスワードが間違っていたり,メールアドレスが存在しなかったりする場合に以下のようなエラーが出るため,Promise でエラーを取得できるように修正した.

{code: "auth/wrong-password", message: "The password is invalid or the user does not have a password."}
{code: "auth/user-not-found", message: "There is no user record corresponding to this identifier. The user may have been deleted."}

Firebase Authentication via Third-Party Providers

「Google 認証」を実装した.と言っても難しいことはあまりなく,提供されている GoogleAuthProvider を使うだけだった.

methods: {
  signInWithGoogle () {
    const provider = new firebase.auth.GoogleAuthProvider()
    firebase.auth().signInWithPopup(provider)
      .catch(error => alert('🤕' + error.message))
      .then(data => console.log(data.user, data.credential.accessToken))
  }
}

Google アカウントに紐付く画像も取得できるため,以下のように画面を実装した.

<div v-if="authUser">
  <h2>Signed in as {{authUser.email}}</h2>
  <img :src="authUser.photoURL" height="150">
  <p>What's up, {{authUser.displayName || 'friend'}}?</p>
  <button @click="signOut">Sign out</button>
</div>

f:id:kakku22:20180522145640p:plain

(Google 認証に成功した)

f:id:kakku22:20180522145655p:plain

(Firebase Authentication コンソールでも Google プロバイダになっていた)

Update Firebase Authentication User Profile

次はプロフィール(今回は名前と画像 URL)を変更できるようにした.メソッドは以下のように authUser.updateProfile を使った.

methods: {
  updateProfile () {
    this.authUser.updateProfile({
      displayName: this.displayName,
      photoURL: this.photoURL
    })
  }
}

f:id:kakku22:20180522145912p:plain

(プロフィールを変更できるようになった)

Update Firebase Authentication User Email and Password

さらに「メール認証」のときにメールアドレスを変更できるようにした.本当に全て簡単にできてしまう.

methods: {
  updateEmail () {
    this.authUser.updateEmail(this.email)
  },
  updatePassword () {
    this.authUser.updatePassword(this.newPassword)
      .then(() => { this.newPassword = null })
      .catch(error => alert('🤕' + error.message))
  }
}

Link Multiple Firebase Authentication Providers to One User Account

なんと Firebase Authentication を使うと「メール認証」と「Google 認証」など,複数のプロバイダを紐付けることもできる.Firebase Authentication の linkWithPopupunlink を使うだけだった.

methods: {
  linkGoogle () {
    const provider = new firebase.auth.GoogleAuthProvider()
    this.authUser.linkWithPopup(provider)
      .catch(error => alert('🤕' + error.message))
  },
  unlinkGoogle () {
    this.authUser.unlink('google.com')
  },
}

f:id:kakku22:20180522150157p:plain

(複数のプロバイダに紐付けることができた)

Additional User Data and Firebase Authentication

Firebase Authentication で管理できるプロフィール情報は限られているため,例えば「ウェブサイト/誕生日など」任意の追加情報を登録できる機能を実装した.追加情報を保存するデータストアは Firebase Realtime Database だった.詳細は別のコース「Vue.js + Firebase Realtime Database」を参照してもらえればと.

f:id:kakku22:20180522144739p:plain

(追加情報を登録できるようになった)

f:id:kakku22:20180522151258p:plain

(Firebase Realtime Database のデータ構造)

Protected Routes with Vue Router, Firebase Authentication and Vuex

Coming Soon !

まとめ

  • Vue School が公開している無料コース「Vue.js + Firebase Authentication」を受講した
  • 1,2時間で Firebase Authentication の機能概要と実装イメージを把握することができた
  • こんなに簡単に認証機能の実装ができてしまって良いのだろうか?(ビックリ 👀)
  • 追加のプロフィールを情報を Firebase Realtime Database に保存する実装もあり実践的だった