diff --git a/server.js b/server.js index ce5a413e3c2b14a6e2eb3e642edb98c894ca9f91..628e1e6c19f3442b7ed1c0c51e535fd25aad9e7c 100644 --- a/server.js +++ b/server.js @@ -23,6 +23,9 @@ const isLoggedIn = (req, res, next) => { } }; +const userRoutes = require("./routes/user"); // เพิ่มการเรียกใช้งาน +app.use("/user", userRoutes); // เพิ่มการใช้งาน user routes + // Session Configuration app.use(session({ secret: process.env.SESSION_SECRET || "mysecret", diff --git a/shop-routes/user.js b/shop-routes/user.js new file mode 100644 index 0000000000000000000000000000000000000000..38ddbe0bc73ddee38d13acecbc93a87b3951ef92 --- /dev/null +++ b/shop-routes/user.js @@ -0,0 +1,36 @@ +const express = require("express"); +const bcrypt = require("bcrypt"); +const pool = require("../config/database"); +const router = express.Router(); + +// แสดงฟอร์มเปลี่ยนรหัสผ่าน +router.get("/change-password", (req, res) => { + res.render("change-password"); +}); + +// อัปเดตรหัสผ่านใหม่ +router.post("/change-password", async (req, res) => { + try { + const { email, newPassword } = req.body; + if (!email || !newPassword) { + return res.status(400).send("กรุณากรอกข้อมูลให้ครบ"); + } + + // ค้นหาผู้ใช้ + const [users] = await pool.execute("SELECT * FROM users WHERE email = ?", [email]); + if (users.length === 0) { + return res.status(400).send("ไม่พบอีเมลนี้ในระบบ"); + } + + // เข้ารหัสรหัสผ่านใหม่ + const hashedPassword = await bcrypt.hash(newPassword, 10); + await pool.execute("UPDATE users SET password = ? WHERE email = ?", [hashedPassword, email]); + + res.send("เปลี่ยนรหัสผ่านสำเร็จ! <a href='/login'>เข้าสู่ระบบ</a>"); + } catch (error) { + console.error(error); + res.status(500).send("เกิดข้อผิดพลาด"); + } +}); + +module.exports = router; \ No newline at end of file diff --git a/views/login.ejs b/views/login.ejs index 5f6b531138e4a756337b1244f5463f697fa21ada..fb7cf796c1f11692ab6bb40d8df6acbab4b6eecd 100644 --- a/views/login.ejs +++ b/views/login.ejs @@ -19,6 +19,8 @@ <input type="password" id="password" name="password" required> </div> <button type="submit">Login</button> + <p><a href="/user/change-password">ลืมรหัสผ่าน?</a></p> <!-- เพิ่มลิงก์เปลี่ยนรหัสผ่าน --> + <p>Don't have an account? <a href="/register">Register</a></p> </form> </div> </body>