// middleware/authMiddleware.js // Middleware to protect routes by verifying JWT const jwt = require('jsonwebtoken'); require('dotenv').config(); const JWT_SECRET = process.env.JWT_SECRET; const authenticateToken = (req, res, next) => { // Get token from the 'token' cookie const token = req.cookies.token; // Enhanced debug logging console.log('Auth Request:', { path: req.path, method: req.method, contentType: req.headers['content-type'], accept: req.headers.accept, hasToken: !!token, // Log if token exists (true/false) cookies: Object.keys(req.cookies) // Log all cookie names }); // More precise API request detection - already good const isApiRequest = req.path.startsWith('/api/') || req.xhr || (req.headers['content-type'] && req.headers['content-type'].includes('application/json')) || (req.headers.accept && req.headers.accept.includes('application/json')); // If no token is present, deny access if (!token) { console.log('No token found, request is API?', isApiRequest); // If the request is for an API endpoint, return 401 Unauthorized if (isApiRequest) { return res.status(401).json({ message: 'Zugriff verweigert. Nicht authentifiziert.' }); } // Otherwise, redirect to the login page return res.redirect('/login'); } // Verify the token with better error reporting jwt.verify(token, JWT_SECRET, (err, user) => { if (err) { console.error('JWT Verification Error:', err.message, err.name); // If token is invalid or expired if (isApiRequest) { // Clear the invalid cookie and return 403 Forbidden for API requests res.clearCookie('token'); return res.status(403).json({ message: 'Token ungültig oder abgelaufen.' }); } // Clear the invalid cookie and redirect to login for page requests res.clearCookie('token'); return res.redirect('/login'); } // If token is valid, attach the decoded user information (payload) to the request object req.user = user; // Add debug logging for successful auth console.log('Authentication successful for user:', user.username, 'user ID:', user.id); next(); }); }; module.exports = authenticateToken;