const express = require('express'); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const { body, validationResult } = require('express-validator'); const { getDatabase } = require('../config/database'); const { JWT_SECRET } = require('../middleware/auth'); const router = express.Router(); // Login router.post('/login', [ body('email').isEmail().normalizeEmail(), body('password').isLength({ min: 6 }) ], async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password } = req.body; const db = getDatabase(); const user = db.prepare('SELECT * FROM users WHERE email = ? AND is_active = 1').get(email); if (!user) { return res.status(401).json({ error: 'Invalid credentials' }); } const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) { return res.status(401).json({ error: 'Invalid credentials' }); } const token = jwt.sign( { id: user.id, email: user.email, role: user.role, firstName: user.first_name, lastName: user.last_name }, JWT_SECRET, { expiresIn: '24h' } ); db.prepare('UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(user.id); res.json({ token, user: { id: user.id, email: user.email, firstName: user.first_name, lastName: user.last_name, role: user.role, department: user.department, designation: user.designation, location: user.location } }); } catch (error) { console.error('Login error:', error); res.status(500).json({ error: 'Server error' }); } }); // Register (Admin only) router.post('/register', [ body('email').isEmail().normalizeEmail(), body('password').isLength({ min: 6 }), body('firstName').trim().notEmpty(), body('lastName').trim().notEmpty(), body('role').isIn(['admin', 'chro', 'head_pms', 'manager', 'team_lead', 'member']) ], async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { email, password, firstName, lastName, role, department, designation, reportingManagerId, location, employeeCode, grade } = req.body; const db = getDatabase(); const existingUser = db.prepare('SELECT id FROM users WHERE email = ?').get(email); if (existingUser) { return res.status(400).json({ error: 'User already exists' }); } const hashedPassword = await bcrypt.hash(password, 10); const result = db.prepare(` INSERT INTO users (email, password, first_name, last_name, role, department, designation, reporting_manager_id, location, employee_code, grade) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run(email, hashedPassword, firstName, lastName, role, department, designation, reportingManagerId, location, employeeCode, grade); res.status(201).json({ id: result.lastInsertRowid, message: 'User created successfully' }); } catch (error) { console.error('Registration error:', error); res.status(500).json({ error: 'Server error' }); } }); // Get current user router.get('/me', async (req, res) => { try { const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token' }); } const decoded = jwt.verify(token, JWT_SECRET); const db = getDatabase(); const user = db.prepare(` SELECT u.*, rm.first_name as manager_first_name, rm.last_name as manager_last_name, rm.email as manager_email FROM users u LEFT JOIN users rm ON u.reporting_manager_id = rm.id WHERE u.id = ? `).get(decoded.id); if (!user) { return res.status(404).json({ error: 'User not found' }); } delete user.password; res.json({ user }); } catch (error) { res.status(401).json({ error: 'Invalid token' }); } }); // Change password router.post('/change-password', [ body('currentPassword').notEmpty(), body('newPassword').isLength({ min: 6 }) ], async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } const { currentPassword, newPassword } = req.body; const token = req.headers.authorization?.split(' ')[1]; if (!token) { return res.status(401).json({ error: 'No token' }); } const decoded = jwt.verify(token, JWT_SECRET); const db = getDatabase(); const user = db.prepare('SELECT * FROM users WHERE id = ?').get(decoded.id); const isValid = await bcrypt.compare(currentPassword, user.password); if (!isValid) { return res.status(400).json({ error: 'Current password is incorrect' }); } const hashedPassword = await bcrypt.hash(newPassword, 10); db.prepare('UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?').run(hashedPassword, decoded.id); res.json({ message: 'Password changed successfully' }); } catch (error) { res.status(500).json({ error: 'Server error' }); } }); module.exports = router;