diff --git a/backend/src/middleware/optionalAuthenticateUser.js b/backend/src/middleware/optionalAuthenticateUser.js new file mode 100644 index 0000000..09b3ad5 --- /dev/null +++ b/backend/src/middleware/optionalAuthenticateUser.js @@ -0,0 +1,17 @@ +// middleware/optionalAuthenticateUser.js +import jwt from "jsonwebtoken"; + +const optionalAuthenticateUser = (req, res, next) => { + try { + const token = req.cookies?.token; + if (token) { + const decoded = jwt.verify(token, process.env.JWT_SECRET); + req.user = decoded; + } + } catch (error) { + // Ignore verification errors (expired, invalid) for optional auth + } + next(); +}; + +export default optionalAuthenticateUser; \ No newline at end of file diff --git a/backend/src/server.js b/backend/src/server.js index 7484eaf..eb456bc 100644 --- a/backend/src/server.js +++ b/backend/src/server.js @@ -17,6 +17,7 @@ import { connectRedis } from "./config/redis.js"; // Middleware import rateLimiter from "./middleware/rateLimiter.js"; +import optionalAuthenticateUser from "./middleware/optionalAuthenticateUser.js"; // ==================== CONFIGURATION ==================== dotenv.config(); @@ -48,19 +49,7 @@ if (process.env.NODE_ENV !== "production") { app.use(express.json()); app.use(cookieParser()); -// Optional auth to populate req.user for rateLimiter -const optionalAuthenticateUser = (req, res, next) => { - try { - const token = req.cookies?.token; - if (token) { - const decoded = jwt.verify(token, process.env.JWT_SECRET); - req.user = decoded; - } - } catch (error) { - // Ignore verification errors (expired, invalid) for optional auth - } - next(); -}; + // Rate limiting and optional auth applied only to API routes app.use("/api", rateLimiter);