From a06e146cdafa9d675633790db4e4dd95fa681126 Mon Sep 17 00:00:00 2001 From: 65160132 <65160132@go.buu.ac.th> Date: Wed, 19 Mar 2025 14:09:18 +0700 Subject: [PATCH] login and register --- controllers/indexController.js | 2 +- controllers/loginController.js | 36 +++++++++++++++++++++++--- controllers/registerController.js | 27 ++++++++++++++++--- db.js | 14 ++++++++++ index.js | 43 +++++++------------------------ views/login.ejs | 4 +-- views/register.ejs | 6 ++--- 7 files changed, 87 insertions(+), 45 deletions(-) create mode 100644 db.js diff --git a/controllers/indexController.js b/controllers/indexController.js index b32fd99..7ccb044 100644 --- a/controllers/indexController.js +++ b/controllers/indexController.js @@ -1,3 +1,3 @@ module.exports = (req, res) => { - res.render('index') + res.render('index', { message: req.flash('message') }); } \ No newline at end of file diff --git a/controllers/loginController.js b/controllers/loginController.js index 35355ea..0bdf2f3 100644 --- a/controllers/loginController.js +++ b/controllers/loginController.js @@ -1,3 +1,33 @@ -module.exports = (req, res) => { - res.render('login') -} \ No newline at end of file +const bcrypt = require('bcrypt'); +const pool = require('../db'); // แยกไฟล์ connection ใน db.js + +module.exports = { + showLoginPage: (req, res) => { + res.render('login', { message: req.flash('message') }); + }, + + loginUser: async (req, res) => { + const { email, rpassword } = req.body; + try { + const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]); + if (rows.length === 0) { + req.flash('message', 'Email not found'); + return res.redirect('/login'); + } + + const user = rows[0]; + const match = await bcrypt.compare(rpassword, user.password); + if (!match) { + req.flash('message', 'Password incorrect'); + return res.redirect('/login'); + } + + // login success (สามารถสร้าง session ได้ที่นี่) + req.flash('message', 'Login successful'); + res.redirect('/'); + } catch (err) { + console.error(err); + res.status(500).send('Server error'); + } + } +}; diff --git a/controllers/registerController.js b/controllers/registerController.js index 70f084c..f2b6835 100644 --- a/controllers/registerController.js +++ b/controllers/registerController.js @@ -1,3 +1,24 @@ -module.exports = (req, res) => { - res.render('register') -} \ No newline at end of file +const bcrypt = require('bcrypt'); +const pool = require('../db'); + +module.exports = { + showRegisterPage: (req, res) => { + res.render('register', { message: req.flash('message') }); + }, + + registerUser: async (req, res) => { + const { email, rpassword } = req.body; + + try { + const hashedPassword = await bcrypt.hash(rpassword, 10); + const query = 'INSERT INTO users (email, password) VALUES (?, ?)'; + await pool.execute(query, [email, hashedPassword]); + + req.flash('message', 'User registered successfully. Please log in.'); + res.redirect('/login'); + } catch (err) { + console.error('Error inserting user:', err); + res.status(500).send('Error occurred'); + } + } +}; diff --git a/db.js b/db.js new file mode 100644 index 0000000..c3a3add --- /dev/null +++ b/db.js @@ -0,0 +1,14 @@ +const mysql = require('mysql2/promise'); + +const pool = mysql.createPool({ + host: process.env.DB_HOST || "node77528-env-7116441.th2.melon.cloud", + port: process.env.DB_PORT || "11789", + user: process.env.DB_USER || "root", + password: process.env.DB_PASSWORD || "THOxlv44950", + database: process.env.DB_NAME || "db", + waitForConnections: true, + connectionLimit: 10, + queueLimit: 0 +}); + +module.exports = pool; diff --git a/index.js b/index.js index 8a66e1e..7b008b8 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,5 @@ const express = require('express'); const bodyParser = require('body-parser'); -const mysql = require('mysql2/promise'); const session = require('express-session'); const flash = require('connect-flash'); @@ -9,47 +8,25 @@ app.use(express.static('public')); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({ extended: true })); +app.use(session({ + secret: 'secretkey', + resave: false, + saveUninitialized: true +})); app.use(flash()); app.set('view engine', 'ejs'); -let port = process.env.PORT || 3000; - -// Controllers const indexController = require('./controllers/indexController'); const loginController = require('./controllers/loginController'); const registerController = require('./controllers/registerController'); -//conectdb -const pool = mysql.createPool({ - host: process.env.DB_HOST || "10.104.21.141" , - port: process.env.DB_PORT || "3306", - user: process.env.DB_USER || "root", - password: process.env.DB_PASSWORD || "THOxlv44950" , - database: process.env.DB_NAME || "db", - waitForConnections: true, - connectionLimit: 10, - queueLimit: 0 -}); -async function testConnection() { - try { - const connection = await pool.getConnection(); - await connection.ping(); - console.log('Database connection succeeded.'); - connection.release(); - } catch (err) { - console.error('Database connection failed:', err); - process.exit(1); // Terminate the app if the database connection fails - } - } -testConnection(); - - - - app.get('/', indexController); -app.get('/login', loginController); -app.get('/register', registerController); +app.get('/login', loginController.showLoginPage); +app.post('/user/login', loginController.loginUser); +app.get('/register', registerController.showRegisterPage); +app.post('/user/register', registerController.registerUser); +const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server running on port ${port}`); }); diff --git a/views/login.ejs b/views/login.ejs index 7644d72..0b4d5d2 100644 --- a/views/login.ejs +++ b/views/login.ejs @@ -134,11 +134,11 @@ <div class="form-floating"> <label for="floatingInput">Email address</label> - <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com"> + <input type="email" class="form-control" id="floatingInput" name="email" placeholder="name@example.com"> </div> <div class="form-floating"> <label for="floatingPassword">Password</label> - <input type="password" class="form-control" id="floatingPassword" placeholder="Password"> + <input type="password" class="form-control" id="floatingPassword" name="rpassword" placeholder="Password"> </div> <div class="form-check text-start my-3"> diff --git a/views/register.ejs b/views/register.ejs index 4eb40dc..ab9f92a 100644 --- a/views/register.ejs +++ b/views/register.ejs @@ -129,16 +129,16 @@ </svg> <main class="form-signin w-100 m-auto"> - <form action="/user/login" method="POST"> + <form action="/user/register" method="POST"> <h1 class="h3 mb-3 fw-normal">Sign up</h1> <div class="form-floating"> <label for="floatingInput">Email address</label> - <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com"> + <input type="email" class="form-control" id="floatingInput" name="email" placeholder="name@example.com"> </div> <div class="form-floating"> <label for="floatingPassword">Password</label> - <input type="password" class="form-control" id="floatingPassword" placeholder="Password"> + <input type="password" class="form-control" id="floatingPassword" name="rpassword" placeholder="Password"> </div> <div class="form-check text-start my-3"> -- GitLab