import jwt from 'jsonwebtoken'; const SECRET = process.env.JWT_SECRET || 'change-me-to-a-long-random-string'; const EXPIRY = '8h'; export function signToken(user) { return jwt.sign({ id: user.id, username: user.username, role: user.role }, SECRET, { expiresIn: EXPIRY, }); } export function verifyToken(token) { try { return jwt.verify(token, SECRET); } catch { return null; } } // Accepts token from Authorization: Bearer or the `nn_token` cookie. export function requireAuth(req, res, next) { const header = req.get('authorization') || ''; const bearer = header.startsWith('Bearer ') ? header.slice(7) : null; const token = bearer || req.cookies?.nn_token; const payload = token && verifyToken(token); if (!payload) return res.status(401).json({ error: 'unauthorized' }); req.user = payload; next(); }