Fix token verification and clean up comments#101
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This pull request hardens the verifyToken Express middleware by performing real JWT signature verification and improving error handling around missing/malformed credentials.
Changes:
- Add a server-side configuration guard to ensure
JWT_SECRETis set before attempting verification. - Validate/parse the
Authorizationheader and token more explicitly, with clearer failure messages. - Replace
jwt.decodewithjwt.verify(HS256-restricted) and validate the decoded payload containssub.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if (err.name === 'TokenExpiredError') { | ||
| return res.status(401).json('Token expired'); | ||
| } | ||
|
|
There was a problem hiding this comment.
jsonwebtoken can throw NotBeforeError (token used before nbf). Currently that case would fall through to the generic 500 handler, making a client/token issue look like a server error. Consider handling NotBeforeError explicitly (likely as 401) alongside the other JWT error branches.
| if (err.name === 'NotBeforeError') { | |
| return res.status(401).json('Token not active'); | |
| } |
| return res.status(401).json('Authorization header missing'); | ||
| } | ||
|
|
||
| if (!authHeader.startsWith('Bearer ')) { | ||
| return res.status(401).json('Invalid authorization format'); |
There was a problem hiding this comment.
Error responses in this middleware are returned as JSON strings (e.g., res.status(...).json('...')), but the rest of the API appears to consistently return objects like { message: ... } / { error: ... } (see e.g. Controllers/OrganizerDashboard.controller.js:47 and Middleware/paginate.js:6). Returning plain strings can make client-side error handling inconsistent; consider standardizing these responses to the same object shape used elsewhere.
| try { | ||
| const decoded = jwt.verify(token, process.env.JWT_SECRET, { | ||
| algorithms: ['HS256'], // match how you sign tokens | ||
| }); | ||
|
|
There was a problem hiding this comment.
There are existing middleware unit tests (e.g. tests/middlewares/paginate.test.js), but no coverage for this updated token-verification behavior. Adding tests for the main branches (missing header, malformed Bearer scheme, expired token, invalid signature, valid token payload w/ sub) would help prevent regressions.
|
@ordo-chao please review comments from coderabbit |
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if (!process.env.JWT_SECRET) { | ||
| console.error('JWT_SECRET is not configured'); | ||
| return res.status(500).json('Internal server error'); | ||
| } |
There was a problem hiding this comment.
This middleware returns raw strings via res.json(...) (e.g., on 500 here). Elsewhere in the codebase responses are consistently JSON objects with message/error fields (e.g., Middleware/paginate.js:6, Middleware/upload.js:72). Consider returning a structured object here as well (and applying the same shape to the other error returns in this middleware) to keep the API response schema consistent for clients.
| const [scheme, token] = authHeader.trim().split(/\s+/, 2); | ||
|
|
||
| if (!scheme || scheme.toLowerCase() !== 'bearer') { | ||
| return res.status(401).json('Invalid authorization format'); | ||
| } | ||
| if (!token) { | ||
| return res.status(401).json('Token missing'); | ||
| } |
There was a problem hiding this comment.
authHeader.trim().split(/\s+/, 2) will accept headers with extra segments (e.g., "Bearer <token> extra") by silently ignoring everything after the token. Consider parsing into all parts and requiring exactly 2 segments (Bearer + token) to avoid accepting malformed Authorization headers.
| // --- 1. Check server configuration --- | ||
| if (!process.env.JWT_SECRET) { | ||
| console.error('JWT_SECRET is not configured'); | ||
| return res.status(500).json('Internal server error'); | ||
| } |
There was a problem hiding this comment.
This will console.error on every request when JWT_SECRET is unset, which can flood logs under load. Consider failing fast at process startup (preferred) or at least reading/caching the secret at module load and logging once, while still returning 500 for requests.
| try { | ||
| const decoded = jwt.verify(token, process.env.JWT_SECRET, { | ||
| algorithms: ['HS256'], // match how you sign tokens | ||
| }); | ||
|
|
||
| if (!decoded || typeof decoded !== 'object' || !decoded.sub) { | ||
| return res.status(401).json('Invalid token payload'); | ||
| } |
There was a problem hiding this comment.
The verification logic and expanded error cases are now more complex (config missing, malformed header, missing token, expired token, invalid token, invalid payload). The repo already has middleware unit tests (e.g., tests/middlewares/paginate.test.js), but there are no tests covering verifyToken. Consider adding unit tests for the main branches to prevent regressions.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This pull request improves the
verifyTokenmiddleware inMiddleware/jwt_token_verification.jsby strengthening JWT verification, adding better error handling, and clarifying error messages. The changes make the authentication process more robust and informative for both developers and API consumers.Error handling and validation improvements:
JWT_SECRETis configured, returning a 500 error if not set.jwt.decodetojwt.verifyfor actual signature verification and restricted to theHS256algorithm.subproperty.