Newer
Older
instance / sisaku / server.js
@Nakagawa.K Nakagawa.K on 29 Nov 1 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許可



// ----------------------------
// 新規登録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('登録失敗(既に登録済み?)');


// ----------------------------
// ログイン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');
});