From 5f5d913988543ddc2c1355ea60009d4feaa56df4 Mon Sep 17 00:00:00 2001 From: Atiwit Pattanapukdee <65160394@go.buu.ac.th> Date: Tue, 18 Mar 2025 22:49:15 +0700 Subject: [PATCH] Project Round 5 --- controllers/tourController.js | 56 ++++++++++++++++++++++++++++++++++- routes/tourRoutes.js | 4 +-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/controllers/tourController.js b/controllers/tourController.js index 027d0c6..48091bc 100644 --- a/controllers/tourController.js +++ b/controllers/tourController.js @@ -74,13 +74,67 @@ exports.postLogin = async (req, res) => { } }; - exports.Logout = (req, res) => { req.session.destroy(() => { res.redirect('/'); }); }; +//Profile +exports.getProfilePage = async (req, res) => { + if (!req.session.userId) { + return res.redirect('/login'); + } + + try { + const user = await User.findById(req.session.userId); + res.render('profile', { user }); + } catch (err) { + console.error(err); + res.redirect('/'); + } +}; +exports.getEditProfilePage = async (req, res) => { + if (!req.session.userId) { + return res.redirect('/login'); + } + + try { + const user = await User.findById(req.session.userId); + res.render('edit-profile', { user }); + } catch (err) { + console.error(err); + res.redirect('/profile'); + } +}; + +exports.updateProfile = async (req, res) => { + const { name, email, password } = req.body; + + if (!name || !email) { + return res.status(400).send('Name and Email are required'); + } + + try { + let user = await User.findById(req.session.userId); + + // อัปเดตชื่อและอีเมล + user.name = name; + user.email = email; + + // อัปเดตพาสเวิร์ดถ้ามีการกรอก + if (password) { + user.password = await bcrypt.hash(password, 10); + } + + await user.save(); + res.redirect('/profile'); + } catch (err) { + console.error(err); + res.status(500).send('Error updating profile'); + } +}; + //CRUD // แสดงฟอร์มสร้างทัวร์ exports.getCreateTour = (req, res) => { diff --git a/routes/tourRoutes.js b/routes/tourRoutes.js index 7eb0f54..df75860 100644 --- a/routes/tourRoutes.js +++ b/routes/tourRoutes.js @@ -28,7 +28,7 @@ router.get('/delete/:id', tourController.deleteTour); //ลบทัวร์ router.get('/search', tourController.searchTours); //หน้าค้นหาทัวร์ //Profile -router.get('/profile', userController.getProfilePage);//หน้าโปรไฟล์ -router.post('/edit-profile', userController.updateProfile);// อัปเดตข้อมูลโปรไฟล์ +router.get('/profile', tourController.getProfilePage);//หน้าโปรไฟล์ +router.post('/edit-profile', tourController.updateProfile);// อัปเดตข้อมูลโปรไฟล์ module.exports = router; -- GitLab