LoginSignup
2
0

More than 3 years have passed since last update.

プログラミング素人のIoTサービス開発 -ログイン認証-

Last updated at Posted at 2020-05-27

はじめに

2020年3月からプログラミングの勉強を始めて、7月までにWebサービス制作に挑戦しているプログラミング素人の制作記録です。

自分の技術レベル

・ProgateでHTML/CSS、JavaScript、Node.JSを受けた
・Expressフレームワークでget通信とpost通信を扱えるようになってきた
・JSのPromeseの概念が少しだけ理解できてきた
・obnizを触ったことがある
 https://note.com/hiromae/n/n4850983a3f92

目標制作物&必要な技術ロードマップ

熱くなる季節に向けて、熱中症予防のための温度検知サービスの制作に取り組んでいます。

身近な問題をIoTで解決できないか考えてみた
https://note.com/hiromae/n/n0e4a88bb501c

■現在構想しているサービス像
制作のために今後身につける必要がある技術が山ほどあります。
2020-05-27_22h07_42.png

今回はサービスへのログイン認証サービスに触ってみました。

今回インプットしたもの

Firebase
https://firebase.google.com/?hl=ja

今回のアウトプット

emailとpwをexpressのWebサーバに渡し、Firebaseで認証成功したらログイン後ページに遷移させることができました。

2020-05-27_21h56_43.png
2020-05-27_21h58_15.png

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
      integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
      crossorigin="anonymous"
    />
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
      integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
      crossorigin="anonymous"
    ></script>

    <title>Document</title>
  </head>
  <body>
    <div class="container py-5">
      <form method="POST" action="/login"  id="app">
        <div class="form-group">
          <label for="email">Email address</label>
          <input
            type="email"
            class="form-control"
            id="email"
            aria-describedby="emailHelp"
            name="email"
          />
          <small id="emailHelp" class="form-text text-muted"
            >We'll never share your email with anyone else.</small
          >
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input
            type="password"
            class="form-control"
            id="password"
            name="password"
          />
        </div>
        <div class="form-group form-check">
          <input type="checkbox" class="form-check-input" id="exampleCheck1" />
          <label class="form-check-label" for="exampleCheck1"
            >Check me out</label
          >
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>
    </div>
  </body>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.4/dist/validators.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vuelidate@0.7.4/dist/vuelidate.min.js"></script>

  <script>
    Vue.use(window.vuelidate.default);
    const { required, email } = window.validators;

    const app = new Vue({
      el: "#app",
      data: {
        title: "入力フォームバリデーション",
        email: "",
        password: "",
      },
      validations: {
        email: {
          required,
        },
      },
      methods: {
        submitForm() {
          console.log("submit");
        },
      },
    });
  </script>
</html>
const express = require("express");
const app = express();

//Firebaseモジュールの読み込み
const firebase = require("firebase/app");
require("firebase/auth");

//Firebaseの初期化
var firebaseConfig = {
  apiKey: "",
  authDomain: "",
  databaseURL: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => {
  res.render("index.ejs");
});

//ログインボタン押したときの処理
app.post("/login", (req, res) => {
  console.log(req.body.email);
  console.log(req.body.password);
  // ログイン処理の定義
  let handlerLogin = async function () {
    console.log("handlerLogin");
    try {
      const resSignInWithEmailAndPassword = await firebase
        .auth()
        .signInWithEmailAndPassword(req.body.email, req.body.password);
      console.log("↓resSignInWithEmailAndPasswordをconsole.log↓");
      console.log(resSignInWithEmailAndPassword.email);
      res.render("main.ejs");
    } catch (error) {
      console.log(error);
      const errorCode = error.code;
      const errorMessage = error.message;
      if (errorCode === "auth/wrong-password") {
        console.log("Wrong password.");
        res.render("pwWrong.ejs");
      } else {
        console.log(errorMessage);
      }
    }
  };
  handlerLogin();
});

app.listen(process.env.PORT || 8080);
console.log("server listen...");

振り返り

・これで認証したって言えるのだろうか・・・?
・認証後は確かセッション情報を保有してそれによってログイン状態を保つとか聞いたことあるけど・・・

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