省エネ

Flutter、vue3修行中。

【Vue】【Quasar】quasarアプリにfirebase auth のメールリンクを追加する

qkuronekop.hatenablog.jp

先日からvue.jsでアプリを作っているのですが、ユーザーを特定したいので認証機能を入れてみようと思います。
認証方法は今の所2種類を考えています。

これらの認証方法をFirebase Authenticationを使っていれてみようと思います。

Firebase を導入

f:id:qkuroneko:20190816113825p:plain:w320

firebaseを使ったことがある方ならお分かりかと思いますが、firebase consoleのAuthenticationメニューを開き、「ログイン方法」タブから「メール/パスワード」をONにします。
私の場合には、Google認証もいずれ追加したいと思っているのでこちらもONにしています。

今回はパスワードなしにしたいと思いますので、「パスワードなしでログインする」もONにしています。

src/router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import firebase from 'firebase';

import routes from './routes';


Vue.use(VueRouter);


const firebaseConfig = {
  apiKey: '<自分のやつ>',
  authDomain: '<自分のやつ>',
  databaseURL: '<自分のやつ>',
  projectId: '<自分のやつ>',
  storageBucket: '',
  messagingSenderId: '<自分のやつ>',
  appId: '<自分のやつ>',
};

firebase.initializeApp(firebaseConfig);

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation
 */

export default function (/* { store, ssrContext } */) {
  const Router = new VueRouter({
    scrollBehavior: () => ({ x: 0, y: 0 }),
    routes,

    // Leave these as is and change from quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    mode: process.env.VUE_ROUTER_MODE,
    base: process.env.VUE_ROUTER_BASE,
  });

  return Router;
}

firebaseConfigの内容はfirebase consoleのsettingを開き、「全般」タブにあるFirebase SDK snippetから確認できます。
ラジオボタンの「構成」をチェックすると上のと同じものをコピーできます。

ただし、コピーしたままだとLintにひっかかるので、上のコードのように修正する必要があります。

メール入力画面

メールアドレスを入力してもらうための新しい画面を作成しました。

f:id:qkuroneko:20190816115116p:plain:w320

MailLink.vue

<template>
  <q-page>
    <p class="q-ma-md">メールアドレスを送信してください。</p>
    <q-input class="q-ma-md" v-model="email" type="email" label="メールアドレス" />
    <q-btn color="primary" class="float-right q-ma-md" @click="toMail">送信</q-btn>
  </q-page>
</template>

<script>

import firebase from 'firebase/app';
import 'firebase/auth';

export default {
  name: 'MailLink',
  data() {
  },
  methods: {
    toMail() {
      const actionCodeSettings = {
        // URL you want to redirect back to. The domain (www.example.com) for this
        // URL must be whitelisted in the Firebase Console.
        url: '<自分のアドレス>',
        // This must be true.
        handleCodeInApp: true,
      };
      firebase.auth().sendSignInLinkToEmail(this.email, actionCodeSettings)
        .then(() => {
          alert('Send mail.');
          // ここでローカルストレージにメールアドレスを保存しておく
         this.$q.localStorage.set('emailForSignIn', this.email);
        })
        .catch((error) => {
          alert(error.message);
        });
    },
  },
};
</script>

urlにはリダイレクト先のURLをいれます。
firebaseのAuthenticationで承認済みドメインに登録されているドメイン以外はエラーになります。

実際にこの画面からメールを送信すると、firebaseからメールが飛んできます。(メールの文章はfirebase consoleから編集できます)
メールに添付されているリンクをクリックすると、URLに書いておいたURLにキー付きでリダイレクトされます。

リダイレクト先モジュールはこんな感じにしました。

SignIn.vue

<template>
  <q-page>
    <p class="flex flex-center">認証中です。</p>
  </q-page>
</template>

<script>
import firebase from 'firebase/app';
import 'firebase/auth';

export default {
  name: 'SignIn',
  created() {
    if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
      const mailaddress = this.$q.localStorage.getItem('emailForSignIn');
      firebase.auth().signInWithEmailLink(mailaddress, window.location.href)
        .then((result) => {
          console.log(result);
          window.location.href = './#/main';
        })
        .catch((error) => {
          alert(error.message);
        });
    }
  },
};
</script>

保存しておいたメールドレスと、キー付きのURLをsignInWithEmailLink()に渡します。
成功したら、メインの画面へ遷移するという風にしました。

次はGoogle認証を作っていきたいと思います。