Webアプリ

【Webアプリ】出退勤管理アプリ② ログイン機能追加

✨ログイン機能を作る!

まずは簡単なログインを作ります。

今回は

  • メールアドレス+パスワードでログイン
  • Firebase Authentication を使う というやり方でいきます!

🔨やること

【1】Firebase Authenticationを有効にする

  1. Firebaseコンソールを開く
  2. 左側メニューの「Build」→「Authentication」をクリック
  3. 「はじめる」を押す
  4. 「サインイン方法」タブを開く
  5. 「メール/パスワード」をクリックして
    ✅ 「有効にする」にチェック → 保存!

これで、メールとパスワードでログインできる準備完了です!

【2】ログイン用のHTMLを作る

次に、VSCodeで新しいファイルを作ります。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>ログイン画面</title>
    <script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.11.0/firebase-auth-compat.js"></script>
</head>
<body>
    <h1>出退勤管理アプリ - ログイン</h1>

    <input type="email" id="email" placeholder="メールアドレス">
    <input type="password" id="password" placeholder="パスワード">
    <button onclick="login()">ログイン</button>

    <p id="message"></p>

    <script>
        // Firebase 設定
        const firebaseConfig = {
           apiKey: "あなたのAPIキー",
            authDomain: "あなたのauthDomain",
            projectId: "あなたのprojectId",
            storageBucket: "あなたのstorageBucket",
            messagingSenderId: "あなたのmessagingSenderId",
            appId: "あなたのappId"
        };

        // Firebase初期化
        firebase.initializeApp(firebaseConfig);
        const auth = firebase.auth();

        // ログイン関数
        function login() {
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            auth.signInWithEmailAndPassword(email, password)
                .then(() => {
                    document.getElementById('message').innerText = "ログイン成功!";
                    // ログイン後にindex.htmlに移動する
                    window.location.href = "index.html";
                })
                .catch((error) => {
                    document.getElementById('message').innerText = "ログイン失敗:" + error.message;
                });
        }
    </script>
</body>
</html>

📌 コードの内容

  • メールとパスワードを入力して「ログイン」ボタンを押すと
  • 正しければ index.html(出退勤ボタン画面)へ飛びます。
  • 間違えたら「ログイン失敗」とエラー表示。

💬 ここまでやると…

ログイン画面 ➡️ 出退勤画面
という流れができるようになります!!