Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions backend/src/middleware/optionalAuthenticateUser.js
Original file line number Diff line number Diff line change
@@ -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;
15 changes: 2 additions & 13 deletions backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

// Middleware
import rateLimiter from "./middleware/rateLimiter.js";
import optionalAuthenticateUser from "./middleware/optionalAuthenticateUser.js";

// ==================== CONFIGURATION ====================
dotenv.config();
Expand Down Expand Up @@ -48,19 +49,7 @@
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);
Expand All @@ -75,7 +64,7 @@
res.status(200).json({
status: "OK",
message: "Server is running",
timestamp: new Date().toISOString(),

Check failure

Code scanning / CodeQL

Missing rate limiting High

This route handler performs
authorization
, but is not rate-limited.
});
});

Expand Down
Loading