From 00aef74f71cd3e616f1f2df903e9f3d0951f15db Mon Sep 17 00:00:00 2001 From: 65160381 <65160381@go.buu.ac.th> Date: Tue, 25 Mar 2025 00:58:59 +0700 Subject: [PATCH] 7 --- app.js | 97 ++++++++++++++++++++++++++++++++++++++++++++ public/login.html | 20 +++++++++ public/register.html | 33 +++++++++++++++ 3 files changed, 150 insertions(+) create mode 100644 public/login.html create mode 100644 public/register.html diff --git a/app.js b/app.js index f8bac85..43fb0af 100644 --- a/app.js +++ b/app.js @@ -57,6 +57,103 @@ app.get('/', (req, res) => { } }); +app.post('/register', async (req, res) => { + const { email, password } = req.body; + + if (!email || !password) { + return res.status(400).json({ error: 'All fields are required' }); + } + + try { + // ตรวจสอบว่า email มีอยู่แล้วหรือไม่ + const [existingUser] = await pool.query( + 'SELECT * FROM users WHERE email = ?', + [email] + ); + + if (existingUser.length > 0) { + return res.status(400).json({ error: 'Email already exists' }); + } + + // เข้ารหัสรหัสผ่านด้วย bcryptjs + const hashedPassword = await bcrypt.hash(password, 10); + + // เพิ่มข้อมูลลงฐานข้อมูล (ใช้แค่ email และ password) + await pool.query( + 'INSERT INTO users (email, password) VALUES (?, ?)', + [email, hashedPassword] + ); + + res.status(201).json({ message: 'User registered successfully' }); + } catch (error) { + console.error('❌ Registration failed:', error); + res.status(500).json({ error: 'Registration failed' }); + } +}); + +app.post('/login', async (req, res) => { + const { email, password } = req.body; + + if (!email || !password) { + return res.status(400).json({ error: 'All fields are required' }); + } + + try { + // ค้นหาผู้ใช้จาก email + const [user] = await pool.query( + 'SELECT * FROM users WHERE email = ?', + [email] + ); + + if (user.length === 0) { + return res.status(404).json({ error: 'User not found' }); + } + + // ตรวจสอบรหัสผ่าน + const isMatch = await bcrypt.compare(password, user[0].password); + + if (!isMatch) { + return res.status(401).json({ error: 'Invalid password' }); + } + + // สร้าง session ให้กับผู้ใช้ + req.session.user = { + id: user[0].user_id, + email: user[0].email + }; + + res.status(200).json({ message: 'Login successful', user: req.session.user }); + } catch (error) { + console.error('❌ Login failed:', error); + res.status(500).json({ error: 'Login failed' }); + } +}); + +app.post('/logout', (req, res) => { + req.session.destroy(err => { + if (err) { + console.error('❌ Logout failed:', err); + return res.status(500).json({ error: 'Logout failed' }); + } + + res.clearCookie('connect.sid'); + res.status(200).json({ message: 'Logout successful' }); + }); +}); + + +const isAuthenticated = (req, res, next) => { + if (req.session.user) { + next(); + } else { + res.status(401).json({ error: 'Unauthorized' }); + } +}; + +app.get('/dashboard', isAuthenticated, (req, res) => { + res.status(200).json({ message: `Welcome ${req.session.user.username}` }); +}); + // Start the server const port = process.env.PORT || 3000; app.listen(port, () => { diff --git a/public/login.html b/public/login.html new file mode 100644 index 0000000..b21ff98 --- /dev/null +++ b/public/login.html @@ -0,0 +1,20 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Login</title> + <link rel="stylesheet" href="styles/login.css"> +</head> +<body> + <div class="login-container"> + <h2>Login</h2> + <form action="/login" method="post"> + <input type="text" placeholder="Username" name="user" required> + <input type="password" placeholder="Password" name="password" required> + <button type="submit">Login</button> + <p>don't have account <a href="register.html">Register</a></p> + </form> + </div> +</body> +</html> \ No newline at end of file diff --git a/public/register.html b/public/register.html new file mode 100644 index 0000000..1faee6f --- /dev/null +++ b/public/register.html @@ -0,0 +1,33 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Register</title> + <link rel="stylesheet" href="styles/register.css"> + <script> + function validatePassword() { + var password = document.getElementById('password').value; + var confirmPassword = document.getElementById('confirm-password').value; + + if (password !== confirmPassword) { + alert("Passwords do not match!"); + return false; + } + return true; + } + </script> +</head> +<body> + <div class="register-container"> + <h2>Register</h2> + <form onsubmit="return validatePassword()" method="POST" action="/register"> + <input type="text" placeholder="Username" name="username" id="username" required> + <input type="email" placeholder="Email" name="email" required> + <input type="password" placeholder="Password" name="password" id="password" required> + <input type="password" placeholder="Confirm Password" name="confirm-password" id="confirm-password" required> + <button type="submit">Register</button> + </form> + </div> +</body> +</html> -- GitLab