LoginSignup
0
2

More than 3 years have passed since last update.

Vue.jsでSPA - [16] へー、FirebaseでWebアプリのログインってこうやるのか

Last updated at Posted at 2020-04-05

はじめに

だいぶ今更感があるのですが、Vue.js で Firebaseの認証をやってみました

つくってみたのはこんな感じ1

モバイルサイズですがWebアプリです。コードは下の方に貼っておきます

out12.gif

やってみたこと

以下のような手順で、調べながらやりました

Firebase SDK を Web アプリに読み込んでおく

公式のとおりに事前設定。要はこんなやつを html に貼り付けるアレ


var firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  messagingSenderId: "sender-id",
  appID: "app-id",
};

Firebase で Authentication を有効にしておく

今回は一番シンプルそうな「メール / パスワード」での認証を有効化2

image.png

公式のサンプルコードで動作確認

このログインのサンプルコードをありがたく使わせてもらいました。公式のここから辿ることができます。見ての通り、ログインにまつわる一通りの動作が実装されています。パスワードリセットなんかも。使ってみると、ボタンの下の null のところにバックエンドとのやりとりが表示されるのでわかりやすくてよい

image.png

試しにこのサンプルコードで SIGN UP したユーザはこんな感じでFirebaseコンソールでみることができる

image.png

サンプルをみながら自分のコードで認証できるようにする

サンプルをみながら Vue.js で書いてみました。簡単なんでペタッと貼っておきます。


<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Basic Page Needs -->
  <meta charset="utf-8">
  <title>KUSA</title>
  <meta name="description" content="">
  <meta name="author" content="">
  <!-- Mobile Specific Metas -->
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- FONT -->
  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
  <!-- CSS -->
  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/skeleton.css">
  <!-- Favicon -->
  <link rel="icon" type="image/png" href="img/kusa-h40.png">
  <!-- Application configuration -->
  <script type="text/javascript" src=".app_config.js"></script>
  <!-- Fontawsome -->
  <script src="https://kit.fontawesome.com/a1763a7d6f.js" crossorigin="anonymous"></script>
  <!-- Vue.js -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>

<div id="app">

<!-- Menu -->
<div class="container" style="margin-top: 20%">
  <p style="text-align: center;"><img src="img/kusa-h60.png"></img></p>
  <input v-model="email" class="u-full-width font-awesome" type="email" placeholder="Email">
  <input v-model="password" class="u-full-width font-awesome" type="password" placeholder="Password">
  <input @click="signIn" class="u-full-width button-primary" type="submit" value="login">
  <input @click="signUp" class="u-full-width" type="submit" value="create account">

  <a href="#" style="text-decoration:none" @click="signOut">Logout</a>
  <a href="#" style="text-decoration:none" class="u-pull-right">Forgot password</a>

  <label style="margin-top: 20px">Error :</label>
  <pre style="margin-top: 0px; margin-bottom: 5px;"><code>{{ message }}</code></pre>
  <label>Current user :</label>
  <pre style="margin-top: 0px; margin-bottom: 5px;"><code>{{ currentUser }}</code></pre>
</div>

</div>

<!-- Insert this script at the bottom of the HTML, but before you use any Firebase services -->
<!-- Add the entire Firebase JavaScript SDK. Replace when go for production -->
<script src="https://www.gstatic.com/firebasejs/6.2.0/firebase.js"></script>

<script>

  firebase.initializeApp(conf.fbc);
  //firebase.analytics();

  // Vue
  var app = new Vue({
    el: '#app',
    data () {
      return {
        email: '',
        password: '',
        message: '',
        currentUser: ''
      }
    },
    methods: {
      signIn: function () {
        app.message = ''; console.log('sign-in pressed');

        firebase.auth().signInWithEmailAndPassword(app.email, app.password).catch(function(error) {
          var errorCode = error.code;
          var errorMessage = error.message;

          app.message = error.message;
          console.log(error.message);

        }).then(function() {
          app.currentUser = firebase.auth().currentUser;
        });
      },
      signUp: function () {
        app.message = ''; console.log('sign-up pressed');
        firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch(function(error) {
          var errorCode = error.code;
          var errorMessage = error.message;

          app.message = error.message;
          console.log(error);
        }).then(function() {
          app.currentUser = firebase.auth().currentUser;
        });
      },
      signOut: function () {
        firebase.auth().signOut().then(function() {
          app.currentUser = firebase.auth().currentUser;
        });
      },
      resetPass: function () {
     // あとで書く
      }
    }
  })
</script>

</body>
</html>

  • firebaseConfig は直書きしたくなかったので外部ファイル .app_config.js から呼ぶようにして、.app_config.jsgitignore しています3
  • ログインしているかどうか、誰でログインしているかは firebase.auth().currentUser に聞けばわかるので便利

これから

Firebase SDK はよくできていて、かなり短時間で認証周りが作れることがわかりました。あとで OAuth 系も触ってみます。そのあと、引き続き、この KUSA アプリ完成までやっていきます!

シリーズ


  1. ffmpeg で mov を gif にしたけど、なんか青っぽい。なんとかならんか 

  2. 有効になってないと、サンプルコードにこんな風に怒られる → The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section. 

  3. 直書きしてもセキュリティ上問題ないし、本番に出すときに Firebase Hosting つかうと、どうせバレるところに設定ファイルがあるようですが、やはり開発中はデータベースなどのエンドポイント知られるのはなんか気になるし、デバッグでルールをフルオープンしたりもあるので念のためこうしてます 

0
2
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
2