no more 401 error for publicly browsing user
This commit is contained in:
@@ -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 };
|
||||
|
||||
Reference in New Issue
Block a user