no more 401 error for publicly browsing user

This commit is contained in:
jackiettran
2025-10-07 11:43:05 -04:00
parent 9a9e96d007
commit 299522b3a6
8 changed files with 1272 additions and 249 deletions

View File

@@ -58,4 +58,40 @@ const authenticateToken = async (req, res, next) => {
}
};
module.exports = { authenticateToken };
// Optional authentication - doesn't return 401 if no token, just continues
const optionalAuth = async (req, res, next) => {
// Try to get token from cookie
let token = req.cookies?.accessToken;
if (!token) {
// No token is fine for optional auth, just continue
req.user = null;
return next();
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const userId = decoded.id;
if (!userId) {
req.user = null;
return next();
}
const user = await User.findByPk(userId);
if (!user) {
req.user = null;
return next();
}
req.user = user;
next();
} catch (error) {
// Token invalid/expired is fine for optional auth
req.user = null;
next();
}
};
module.exports = { authenticateToken, optionalAuth };