const jwt = require("jsonwebtoken"); const { User } = require("../models"); // Import from models/index.js to get models with associations const authenticateToken = async (req, res, next) => { // First try to get token from cookie let token = req.cookies?.accessToken; if (!token) { return res.status(401).json({ error: "Access token required", code: "NO_TOKEN", }); } try { const decoded = jwt.verify(token, process.env.JWT_SECRET); const userId = decoded.id; if (!userId) { return res.status(401).json({ error: "Invalid token format", code: "INVALID_TOKEN_FORMAT", }); } const user = await User.findByPk(userId); if (!user) { return res.status(401).json({ error: "User not found", code: "USER_NOT_FOUND", }); } req.user = user; next(); } catch (error) { // Check if token is expired if (error.name === "TokenExpiredError") { return res.status(401).json({ error: "Token expired", code: "TOKEN_EXPIRED", }); } console.error("Auth middleware error:", error); return res.status(403).json({ error: "Invalid token", code: "INVALID_TOKEN", }); } }; module.exports = { authenticateToken };