Gitlab@Informatics

Skip to content
Snippets Groups Projects
Commit 7cf8376e authored by 65160381's avatar 65160381
Browse files

7.8

parent bdabf532
No related branches found
No related tags found
No related merge requests found
Pipeline #597 passed with warnings
...@@ -106,44 +106,58 @@ app.post('/register', async (req, res) => { ...@@ -106,44 +106,58 @@ app.post('/register', async (req, res) => {
}); });
// Route สำหรับการล็อกอิน
app.post('/login', async (req, res) => { app.post('/login', async (req, res) => {
const { email, password } = req.body; const { email, password } = req.body; // ใช้ email แทน user
if (!email || !password) {
return res.status(400).json({ error: 'All fields are required' });
}
try { try {
const connection = await pool.getConnection();
// ค้นหาผู้ใช้จาก email // ค้นหาผู้ใช้จาก email
const [user] = await pool.query( const [rows] = await connection.query(
'SELECT * FROM users WHERE email = ?', 'SELECT * FROM users WHERE email = ?',
[email] [email]
); );
connection.release();
if (user.length === 0) { if (rows.length > 0) {
return res.status(404).json({ error: 'User not found' });
}
// ตรวจสอบรหัสผ่าน // ตรวจสอบรหัสผ่าน
const isMatch = await bcrypt.compare(password, user[0].password); const match = await bcrypt.compare(password, rows[0].password);
if (match) {
if (!isMatch) { // เก็บข้อมูลผู้ใช้ใน session (แค่ user_id และ email)
return res.status(401).json({ error: 'Invalid password' });
}
// สร้าง session ให้กับผู้ใช้
req.session.user = { req.session.user = {
id: user[0].user_id, id: rows[0].user_id, // user_id ของผู้ใช้
email: user[0].email email: rows[0].email
}; };
console.log("User session:", req.session.user); // เพิ่ม console log เพื่อตรวจสอบ
res.redirect('/'); // ไปที่หน้า home หรือหน้าแรกหลังจากล็อกอิน
return;
} else {
res.status(400).send('Invalid password');
return;
}
} else {
res.status(400).send('User not found');
return;
}
} catch (err) {
console.error('Login error:', err);
res.status(500).send('Login failed');
return;
}
});
res.status(200).json({ message: 'Login successful', user: req.session.user }); // API สำหรับดึงข้อมูลผู้ใช้หลังจากล็อกอิน
} catch (error) { app.get('/api/getUser', (req, res) => {
console.error('❌ Login failed:', error); if (req.session.user) {
res.status(500).json({ error: 'Login failed' }); res.json({
user_id: req.session.user.id, // ส่งข้อมูล user_id จาก session
email: req.session.user.email // ส่งข้อมูล email จาก session
});
} else {
res.status(401).send('User not logged in');
} }
}); });
app.use(express.json()); // สำหรับการ parse ข้อมูลแบบ JSON app.use(express.json()); // สำหรับการ parse ข้อมูลแบบ JSON
app.use(express.urlencoded({ extended: true })); // สำหรับการ parse ข้อมูลแบบ URL-encoded app.use(express.urlencoded({ extended: true })); // สำหรับการ parse ข้อมูลแบบ URL-encoded
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment