OwlCyberSecurity - MANAGER
Edit File: loginRoute.mjs
import svgCaptcha from 'svg-captcha'; import { Buffer } from 'buffer'; import bcrypt from 'bcrypt'; import EmployeeModel from './models/employee.mjs'; app.get('/captcha-base64', (req, res) => { const captcha = svgCaptcha.create({ size: 6, noise: 2, color: true, background: '#ffffff', }); req.session.captcha = captcha.text; // Save the text in session const svgBase64 = Buffer.from(captcha.data).toString('base64'); res.json({ image: `data:image/svg+xml;base64,${svgBase64}`, }); }); app.post('/login', async (req, res) => { const { EmpNo, password, captcha } = req.body; // ✅ Validate captcha if (!captcha || captcha !== req.session.captcha) { return res.status(400).json({ message: 'Invalid captcha' }); } // ✅ Clear session captcha (single-use) req.session.captcha = null; try { const employee = await EmployeeModel.findOne({ where: { EmpNo } }); if (!employee) { return res.status(401).json({ message: 'Invalid employee number' }); } // ✅ Validate password const passwordMatch = await bcrypt.compare(password, employee.password); if (!passwordMatch) { return res.status(401).json({ message: 'Incorrect password' }); } // ✅ Store role and EmpNo in session req.session.user = { EmpNo: employee.EmpNo, role: employee.role || 'view' // default to 'view' if no role found }; return res.status(200).json({ message: 'Login successful', EmpNo: employee.EmpNo, role: employee.role }); } catch (error) { console.error('Login error:', error); return res.status(500).json({ message: 'Server error', error: error.message }); } });