diff --git a/controllers/registerController.js b/controllers/registerController.js index 7daa893e77349591a35cefc5e0ff41a8631db002..c4ac99e14369dd710afa9b152fe884083495cf96 100644 --- a/controllers/registerController.js +++ b/controllers/registerController.js @@ -7,20 +7,35 @@ module.exports = { }, registerUser: async (req, res) => { - const { email, rpassword } = req.body; + const { email, rpassword, confirm_password } = req.body; + + // ตรวจสอบว่ารหัสผ่านทั้งสองตรงกันหรือไม่ + if (rpassword !== confirm_password) { + req.flash('message', 'Passwords do not match!'); + return res.redirect('/register'); + } try { + // ตรวจสอบว่าอีเมลมีอยู่ในระบบหรือไม่ + const [existingUser] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]); + if (existingUser.length > 0) { + req.flash('message', 'Email is already registered.'); + return res.redirect('/register'); + } + + // แฮชรหัสผ่าน const hashedPassword = await bcrypt.hash(rpassword, 10); + + // บันทึกข้อมูลผู้ใช้ในฐานข้อมูล const query = 'INSERT INTO users (email, password) VALUES (?, ?)'; await pool.execute(query, [email, hashedPassword]); + // ส่งข้อความแจ้งเตือนและเปลี่ยนเส้นทางไปที่หน้า login 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'); } - res.redirect('/'); } - };