Newer
Older
instance / sisaku / server.js
@Nakagawa.K Nakagawa.K on 17 Oct 2 KB 追加
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const nodemailer = require('nodemailer');
const path = require('path');
const cors = require('cors');

const app = express();
const db = new sqlite3.Database('./database.sqlite');

app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors()); // 開発用CORS許可

// ユーザーテーブル作成
db.run(`CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT UNIQUE,
    password TEXT
)`);

// Nodemailer 設定(Gmailの場合)
const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'your.email@gmail.com',        // ← Gmailアドレス
        pass: 'your_app_password'            // ← アプリパスワード
    }
});

// ----------------------------
// 新規登録API
// ----------------------------
app.post('/register', async (req, res) => {
    const { email, password } = req.body;
    if (!email || !password) return res.status(400).send("必須項目がありません");

    const hashedPass = await bcrypt.hash(password, 10);

    db.run(
        `INSERT INTO users (email, password) VALUES (?, ?)`,
        [email, hashedPass],
        function(err) {
            if (err) return res.status(400).send('登録失敗(既に登録済み?)');

            // 登録成功メール送信
            const mailOptions = {
                from: 'your.email@gmail.com',
                to: email,
                subject: '新規登録完了',
                text: `登録ありがとうございます。\nあなたのメールアドレス: ${email}`
            };

            transporter.sendMail(mailOptions, (error, info) => {
                if (error) console.error(error);
            });

            res.send('登録成功!メールを確認してください');
        }
    );
});

// ----------------------------
// ログインAPI
// ----------------------------
app.post('/login', (req, res) => {
    const { email, password } = req.body;
    if (!email || !password) return res.status(400).send("必須項目がありません");

    db.get(`SELECT * FROM users WHERE email = ?`, [email], async (err, row) => {
        if (err) return res.status(500).send("サーバーエラー");
        if (!row) return res.status(401).send("ユーザーが存在しません");

        const match = await bcrypt.compare(password, row.password);
        if (match) {
            res.send("ログイン成功");
        } else {
            res.status(401).send("パスワードが違います");
        }
    });
});

// ----------------------------
// サーバー起動
// ----------------------------
app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});