diff --git a/controllers/tourController.js b/controllers/tourController.js index 027d0c6a44dc867e7f9ebc913d7f82809ce7978c..48091bce056e6ad1f2aae7d847f94225dc047cb8 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 7eb0f54ce8c8c29055fab1b9c1881218086fa20b..df75860acd4c25dbede3363c78e699706588abeb 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;