const jwt = require('jsonwebtoken'); const { ADMIN_EMAIL, ADMIN_PASSWORD, API_KEY, JWT_SECRET } = require('./config'); const { findUserByEmail, normalizeEmail, publicUserFields, verifyPassword } = require('./services/userService'); const verifyToken = (req, res, next) => { const authHeader = req.headers.authorization; if (!authHeader) return res.status(403).json({ error: 'No token provided' }); const token = authHeader.split(' ')[1]; if (!token) return res.status(403).json({ error: 'Malformed token' }); jwt.verify(token, JWT_SECRET, (err, decoded) => { if (err) return res.status(401).json({ error: 'Unauthorized' }); req.user = decoded; next(); }); }; const verifySuperAdmin = (req, res, next) => { verifyToken(req, res, () => { if (req.user?.role !== 'super_admin') { res.status(403).json({ error: 'Super admin access required' }); return; } next(); }); }; const authenticateAPIKey = (req, res, next) => { const apiKey = req.headers['x-api-key']; if (apiKey === API_KEY) { next(); return; } res.status(401).json({ error: 'Unauthorized: Invalid API Key' }); }; const buildTokenResponse = (user) => { const token = jwt.sign( { email: user.email, role: user.role, userId: user.id || null }, JWT_SECRET, { expiresIn: '24h' } ); return { token, user }; }; const login = async (email, password) => { const normalizedEmail = normalizeEmail(email); const normalizedPassword = String(password || '').trim(); if (normalizedEmail === normalizeEmail(ADMIN_EMAIL) && normalizedPassword === ADMIN_PASSWORD) { return buildTokenResponse({ id: null, name: 'Super Admin', email: normalizedEmail, role: 'super_admin' }); } const dbUser = await findUserByEmail(normalizedEmail); if (!dbUser || !dbUser.is_active || !verifyPassword(normalizedPassword, dbUser.password_hash)) { return null; } return buildTokenResponse({ ...publicUserFields(dbUser), role: 'user' }); }; module.exports = { verifyToken, verifySuperAdmin, authenticateAPIKey, login };