サルでもわかるWEBプログラミング

フリーソフトのみでホームページ作成

ユーザ用ツール

サイト用ツール


09.emailとpasswordでパスワード制限:index.html


文書の過去の版を表示しています。


09.emailとpasswordでパスワード制限

CodeSandbox上で、Vue.jsとFirebaseを用いて、EmailとPasswordによるパスワード制限機能のあるホームページを作りたいと思います。

方針をたてる

今回作成するGoogle認証アプリは、

  1. トップページに、「Emailとパスワードでログイン」フォームを表示
  2. Emailとと初期パスワードは、あらかじめ、管理者がFirebase上に登録しておく。
  3. ログインしたら、ログイン成功画面に移動
  4. ログイン後の画面に、ログアウトボタンを表示

となります。

  1. emailとパスワードは『Firebase』という場所に保存

するものとします。

今回は、https://qiita.com/sin_tanaka/items/ea149a33bd9e4b388241と、https://www.tohuandkonsome.site/entry/2018/11/19/182438#Eメールとパスワードでユーザー管理する

のソースコードを利用させていただこうと思います。

ソースコード
https://codesandbox.io/s/6xzm6wr2k3

作ったもの

0.用意するもの(開発環境)

パソコン
Chrome(くろーむ、WEBブラウザの一つ)
GitHubアカウント作成済み(無料)
Googleアカウント作成済み(無料)

パソコンは、Windowsパソコンでも、Macでも、かまいませんが、私の場合はWindows 8.1 Proとなります。

今回利用するもの

CodeSandbox
Firebase
Vue 2.5.2
Vuetify 

1.Firebaseで新規プロジェクト(新しいサーバ)を作成

  • 今回は、「firebase-email-auth」という名前で新規プロジェクトを作成しました。

  • 測定管理者間のデータ保護条項と規約の左側のチェックボックスをONにして、右下の「プロジェクトを作成」をクリック。

  • 少し待つと、「新しいプロジェクトの準備ができました」と表示されるので、次へ をクリック。

  • 以下のようなプロジェクトトップ画面になるので、下図のように、「</>」をクリック。

  • 「ウェブアプリにFirebaseを追加」の画面が出てくるので、グレーで表示された部分の中身をメモ帳などにコピーしておきます。これは、後で、CodeSandboxで、ペーストします。

  • プロジェクトトップ画面で、画面左側の列の「開発」をクリック

  • Authentication をクリック

  • ログイン方法 をクリック

  • メール/パスワード をクリック

  • 「有効にする」をON(青色)にして、保存 をクリック

  • 以下のような状態になっています。

2.Firebaseにログイン用メールアドレスとパスワードを入力

今回は、

email: user@example.com
パスワード: 111111

の人にログインできるようにしたいと思います。

  • Firebaseアプリの、「開発」>「Authentication」>「ユーザー」で、「ユーザーを追加」をクリック

  • emailとパスワードを、以下のように入力して、「ユーザーを追加」をクリック

  • 以下のような感じになります。

3. CodeSandboxでVue.jsアプリを作成

  • Vue をクリック

  • 以下のような画面になります。

4. Vuetifyのインストールとindex.htmlの編集

  • CSSフレームワークとして、Vuetifyを用いるために、以下のように、Add Dependencyをクリック

  • Vuetify と入力して、Vuetifyをクリックして、インストール

  • 以下のようになります

  • 次に、vuetifyとfirebaseを利用できるようにするために、index.htmlとsrc/main.jsを編集します。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>CodeSandbox Vue Vuetify Firebase</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"
rel="stylesheet"
/>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase.js"></script>
<script>
// Initialize Firebase
// こちらにはご自身のFirebaseのAPIキーなどをコピペしてください
var config = {
apiKey: "<YOUR-API-KEY>",
authDomain: "xxxxx",
databaseURL: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "1xxxxx"
};
firebase.initializeApp(config);
</script>
</body>
</html>
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import App from "./App";
import Vuetify from "vuetify";
import "vuetify/dist/vuetify.css";
Vue.use(Vuetify);
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: "#app",
components: { App },
template: "<App/>"
});
view raw src_main.js hosted with ❤ by GitHub

この時点では、特に外見に変化はありません。

5. src/components/Home.vueとSecret.vueの作成

  • src/components/Home.vue と、src/components/Secret.vue を新規作成

<template>
<v-app id="inspire">
<v-content>
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex xs12 sm8 md4>
<v-card class="elevation-12">
<v-toolbar dark color="primary">
<v-toolbar-title>Login form</v-toolbar-title>
<v-spacer></v-spacer>
</v-toolbar>
<v-card-text>
<v-form>
<v-text-field
prepend-icon="person"
name="login"
label="Login"
type="text"
></v-text-field>
<v-text-field
id="password"
prepend-icon="lock"
name="password"
label="Password"
type="password"
></v-text-field>
</v-form>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="primary">Login</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-content>
</v-app>
</template>
<script>
export default {
name: "home",
data() {
return {};
}
};
</script>
<template>
<div class="secret">
<v-app id="inspire">
<v-content>
<v-container fluid fill-height>
<v-flex xs12 sm6 offset-sm3>
<v-card>
<v-img
src="https://cdn.vuetifyjs.com/images/cards/desert.jpg"
aspect-ratio="2.75"
></v-img>
<v-card-title primary-title>
<div>
<h3 class="headline mb-0">Kangaroo Valley Safari</h3>
<div>
Located two hours south of Sydney in the <br />Southern
Highlands of New South Wales, ...
</div>
</div>
</v-card-title>
<v-card-actions>
<v-btn flat color="orange">Share</v-btn>
<v-btn flat color="orange">Explore</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-container>
</v-content>
<v-footer height="auto" color="indigo" dark>
<v-layout justify-center row wrap>
<v-flex color="indigo" dark py-3 text-xs-center white--text xs12>
&copy;2018 — <strong>Vuetify</strong>
</v-flex>
</v-layout>
</v-footer>
</v-app>
</div>
</template>
<script>
export default {
name: "secret",
data() {
return {};
}
};
</script>

6. src/App.vueの編集

src/App.vueを以下のように変更して、「ヘッダーとフッター」と、中身としてHome.vueを表示します。

<template>
<div id="app">
<v-toolbar color="indigo" dark fixed app>
<v-toolbar-title>Vuetify Firebase Email Auth</v-toolbar-title>
</v-toolbar>
<Home v-if="!isLogin"></Home> <Secret v-if="isLogin"></Secret>
<v-footer height="auto" color="indigo" dark>
<v-layout justify-center row wrap>
<v-flex color="indigo" dark py-3 text-xs-center white--text xs12>
&copy;2018 — <strong>Vuetify</strong>
</v-flex>
</v-layout>
</v-footer>
</div>
</template>
<script>
import Home from "./components/Home.vue";
import Secret from "./components/Secret.vue";
export default {
name: "App",
data() {
return {
isLogin: false
};
},
components: {
Home: Home,
Secret: Secret
}
};
</script>
<style></style>

(変更前)

(変更後)

ログインしていないので、Home.vueのログイン画面が表示されます。

7. Emailログインの実装

Googleログインより、Email-Passwordログインの方が、難しい。

参考:https://qiita.com/sin_tanaka/items/ea149a33bd9e4b388241

src/components/Home.vueを編集

先に、<template></template>内のbuttonのところを変更します。

v-text-fieldのところに、それぞれ、v-model=“username”と、v-model=“password”を追加します。

また、v-btnのところに、@click=“emailLogin”を追加します。

(変更前1)

              <v-card-text>
                <v-form>
                  <v-text-field
                    prepend-icon="person"
                    name="login"
                    label="Login"
                    type="text"
                  ></v-text-field>
                  <v-text-field
                    id="password"
                    prepend-icon="lock"
                    name="password"
                    label="Password"
                    type="password"
                  ></v-text-field>
                </v-form>
              </v-card-text>
              
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="primary">Login</v-btn>
              </v-card-actions>

(変更後1)

              <v-card-text>
                <v-form>
                  <v-text-field
                    prepend-icon="person"
                    name="username"
                    label="Username"
                    type="text"
                    v-model="username"
                  ></v-text-field>
                  <v-text-field
                    id="password"
                    prepend-icon="lock"
                    name="password"
                    label="Password"
                    type="password"
                    v-model="password"
                  ></v-text-field>
                </v-form>
              </v-card-text>
              
              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="primary" @click="emailLogin">Login</v-btn>
              </v-card-actions>

次に、<script></script>のところにdata()関数と、emailLogin()関数を定義。
(変更前2)

  data: function () {
    return {}
  },

(変更後2)

  data() {
    return {
      username: "",
      password: ""
    };
  },
  methods: {
    emailLogin: function() {
      firebase
        .auth()
        .signInWithEmailAndPassword(this.username, this.password)
        .then(
          user => {
            alert("Success!");
            this.$router.push("/");
          },
          err => {
            alert(err.message);
          }
        );
    }
  }

この時点で、user@example.com, 111111 と入力してLoginボタンをクリックすると、Success!というアラートが表示される。

8. ログイン状態のチェック

サイト上でログイン状態をチェックします。

App.vue内でログイン状態をチェックして、isLoginに格納します。

src/App.vueの<script></script>内に、data関数の後ろに、created関数を定義します。created関数は、Vue.jsがそのcomponentを作成したタイミングで実行されるとのことです。

  created: function() {
    firebase.auth().onAuthStateChanged(user => {
      console.log(user);
      if (user) {
        this.isLogin = true;
      } else {
        this.isLogin = false;
      }
    });
  },

(変更前)

(変更後)

先ほど、ログインしていますので、上記コード変更により、Secret.vueコンポーネントが表示されるようになりました。

9. コンポーネント間の情報の受け渡しとログアウトボタン

src/App.vueがFirebaseから受け取ったユーザー情報userを、src/components/Secret.vueに渡して、Secret.vue上で表示します。

src/App.vueの<template>の<Editor>の部分に、user=“userData”を追加します。
また、<script>のdata関数でuserDataを初期化し、created関数のところで、ログイン状態のときにuserDataにFirebaseからの情報userを格納します。

(変更前1)

(変更後1)

(変更前2)

(変更後2)

src/components/Secret.vue にて、src/App.vueからの情報userを受け取るために、<script>内でpros: [“user”]と記載します。
ログアウトボタンは、<script>内で、buttonを作成して@click=“logout”と記載し、<script>内でlogout()関数を定義します。

(変更前)

(変更後)

画面上の「ログアウト」ボタンを押すと、ログアウトされて、ログインフォームのページ(Home.vue)が表示されます。

完成です。お疲れさまでした。

さらに、

  1. ユーザーがパスワードを忘れてしまった場合のための、パスワード再発行手続き
  2. 誰もがemailとpasswordを登録すればログインできる(サインアップ)

などの実装を追加してもよいかもしれません。

ソースコード

今回参考にした本

以下の本が、写経していて楽しいし、説明もしっかりされていて、Vue.js入門書として非常におすすめです。

リンク


09.emailとpasswordでパスワード制限/index.html.1545446432.txt.gz · 最終更新: 2018/12/22 by adash333

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki