62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
const jwt = require("jsonwebtoken");
|
|
const { User } = require("../models"); // Import from models/index.js to get models with associations
|
|
const logger = require("../utils/logger");
|
|
|
|
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",
|
|
});
|
|
}
|
|
|
|
const reqLogger = logger.withRequestId(req.id);
|
|
reqLogger.error("Auth middleware error", {
|
|
error: error.message,
|
|
stack: error.stack,
|
|
tokenPresent: !!token,
|
|
userId: req.user?.id
|
|
});
|
|
return res.status(403).json({
|
|
error: "Invalid token",
|
|
code: "INVALID_TOKEN",
|
|
});
|
|
}
|
|
};
|
|
|
|
module.exports = { authenticateToken };
|