more secure token handling

This commit is contained in:
jackiettran
2025-09-17 18:37:07 -04:00
parent a9fa579b6d
commit cf6dd9be90
10 changed files with 807 additions and 231 deletions

View File

@@ -2,11 +2,14 @@ const jwt = require("jsonwebtoken");
const { User } = require("../models"); // Import from models/index.js to get models with associations
const authenticateToken = async (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
// First try to get token from cookie
let token = req.cookies?.accessToken;
if (!token) {
return res.status(401).json({ error: "Access token required" });
return res.status(401).json({
error: "Access token required",
code: "NO_TOKEN",
});
}
try {
@@ -14,20 +17,37 @@ const authenticateToken = async (req, res, next) => {
const userId = decoded.id;
if (!userId) {
return res.status(401).json({ error: "Invalid token format" });
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" });
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 or expired token" });
return res.status(403).json({
error: "Invalid token",
code: "INVALID_TOKEN",
});
}
};