-
-
Notifications
You must be signed in to change notification settings - Fork 103
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Restrict Event Booking to Verified Users #433
Restrict Event Booking to Verified Users #433
Conversation
@github-actions[bot] is attempting to deploy a commit to the bunty's projects Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThe changes in this pull request include updates to the Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Thank you for submitting your pull request! 🙌 We'll review it as soon as possible. In the meantime, please ensure that your changes align with our CONTRIBUTING.md. If there are any specific instructions or feedback regarding your PR, we'll provide them here. Thanks again for your contribution! 😊 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 8
🧹 Outside diff range and nitpick comments (6)
backend/routes/eventRouter.js (2)
30-32
: Fix spacing in middleware chain for better readability.
Add spaces after commas in the middleware chain.
-router.post("/create",authenticateCustomer, createEvent);
-router.get("/all",authenticateCustomer, getEvents);
-router.get("/delete",authenticateCustomer, deleteEvent);
+router.post("/create", authenticateCustomer, createEvent);
+router.get("/all", authenticateCustomer, getEvents);
+router.get("/delete", authenticateCustomer, deleteEvent);
30-32
: Consider adding rate limiting and request validation.
Since these endpoints are now protected and handle sensitive operations, consider adding:
- Rate limiting to prevent brute force attacks
- Request validation middleware to ensure proper input format
- Response sanitization to prevent sensitive data leaks
This will enhance the security of the authenticated endpoints.
Example implementation using express-rate-limit
and express-validator
:
const rateLimit = require('express-rate-limit');
const { body, validationResult } = require('express-validator');
const createEventLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5 // limit each IP to 5 create requests per windowMs
});
const createEventValidation = [
body('eventName').trim().notEmpty(),
body('eventDate').isISO8601(),
// Add other validation rules
];
router.post(
"/create",
createEventLimiter,
createEventValidation,
authenticateCustomer,
createEvent
);
frontend/src/components/Pages/Event.jsx (2)
17-18
: Consider implementing error boundaries for navigation failures.
The navigation setup looks good, but consider wrapping the component with an error boundary to gracefully handle navigation failures and cookie access errors.
Also applies to: 36-36
Line range hint 290-292
: Add authentication check to "Book your slot" button.
The "Book your slot" button in the event list should also implement the same authentication and verification checks as the registration button.
- <button className="btn btn-primary bg-[#C3E0DC] p-4 rounded-xl text-md font-medium mt-4 hover:bg-[#FFF9B1]">
- Book your slot
- </button>
+ <button
+ onClick={handleRegisterClick}
+ disabled={isLoading}
+ className={`
+ btn btn-primary bg-[#C3E0DC] p-4 rounded-xl text-md font-medium mt-4
+ ${isLoading ? 'opacity-50 cursor-not-allowed' : 'hover:bg-[#FFF9B1]'}
+ `}
+ >
+ {isLoading ? 'Verifying...' : 'Book your slot'}
+ </button>
README.md (2)
Line range hint 283-504
: Replace hard tabs with spaces in the contributors table.
The contributors table contains hard tabs that should be replaced with spaces for consistent formatting across different editors and platforms.
Apply this formatting change to the table rows:
- <tr>
+ <tr>
🧰 Tools
🪛 Markdownlint
459-459: Column: 1
Hard tabs
(MD010, no-hard-tabs)
460-460: Column: 1
Hard tabs
(MD010, no-hard-tabs)
Authentication requirements missing from API documentation
The PR introduces authentication middleware that requires users to be verified before accessing certain endpoints, but these requirements are not reflected in the API documentation. The README should be updated to:
- Document the authentication header requirement (
Authorization: Bearer <token>
) - Mark which endpoints require authentication
- Include error responses (401, 403) for unauthorized/unverified access
- Add authentication-related endpoints (login, verify account)
🔗 Analysis chain
Line range hint 1-603
: Verify if README changes belong in this PR.
This PR's primary objective is to restrict event booking to verified users, but the README changes only update the contributors section. Consider submitting contributor updates in a separate PR to maintain focused changes and easier review process.
Consider:
- Moving contributor updates to a separate PR
- Adding documentation about the new authentication requirements in the API Documentation section
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if there are any authentication-related changes in this PR
# that would justify updating the README documentation.
# Search for authentication-related changes in the codebase
echo "Searching for authentication-related changes..."
rg -l "isVerified|authCustomer|authentication"
# Search for any updates to API documentation section in README
echo "Checking if README's API documentation was updated..."
rg -l "api/users|authentication|verified" README.md
Length of output: 542
Script:
#!/bin/bash
# Let's examine the actual authentication-related changes and README updates
# Check authentication-related changes in key files
echo "=== Authentication changes in backend/routes/eventRouter.js ==="
rg "isVerified|authCustomer|authentication" backend/routes/eventRouter.js -A 2 -B 2
echo -e "\n=== Authentication middleware implementation ==="
cat backend/middlewares/authCustomer.js
echo -e "\n=== API Documentation section in README ==="
rg "## 🔍 API Documentation" README.md -A 20
Length of output: 3596
🧰 Tools
🪛 Markdownlint
459-459: Column: 1
Hard tabs
(MD010, no-hard-tabs)
460-460: Column: 1
Hard tabs
(MD010, no-hard-tabs)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- README.md (7 hunks)
- backend/middlewares/authCustomer.js (1 hunks)
- backend/routes/eventRouter.js (2 hunks)
- frontend/src/components/Pages/Event.jsx (3 hunks)
🧰 Additional context used
🪛 Markdownlint
README.md
283-283: Column: 1
Hard tabs
(MD010, no-hard-tabs)
284-284: Column: 1
Hard tabs
(MD010, no-hard-tabs)
327-327: Column: 1
Hard tabs
(MD010, no-hard-tabs)
328-328: Column: 1
Hard tabs
(MD010, no-hard-tabs)
371-371: Column: 1
Hard tabs
(MD010, no-hard-tabs)
372-372: Column: 1
Hard tabs
(MD010, no-hard-tabs)
459-459: Column: 1
Hard tabs
(MD010, no-hard-tabs)
460-460: Column: 1
Hard tabs
(MD010, no-hard-tabs)
503-503: Column: 1
Hard tabs
(MD010, no-hard-tabs)
504-504: Column: 1
Hard tabs
(MD010, no-hard-tabs)
🔇 Additional comments (2)
backend/routes/eventRouter.js (1)
8-8
: LGTM! Middleware import is correctly implemented.
frontend/src/components/Pages/Event.jsx (1)
38-45
: Verify backend route for user verification.
Let's ensure the backend route for user verification is properly implemented.
✅ Verification successful
Authentication flow is properly implemented in the backend
The code is correctly using cookies for authentication, and the backend has proper token verification through middleware:
- Token verification is implemented in
backend/middlewares/authCustomer.js
- Authentication middleware is properly imported and used in event routes
- The frontend's approach of checking
authToken
cookie aligns with the backend's authentication flow
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the verification endpoint exists in the backend routes
rg -A 5 "router\.(get|post|put|delete)\s*\(['\"]\/verify['\"]" backend/
Length of output: 232
Script:
#!/bin/bash
# Search for authentication-related routes in the backend
rg -A 5 "router\.(get|post|put|delete)\s*\(\s*['\"].*auth" backend/
# Search for token verification or validation logic
rg -A 5 "(verify|validate).*[Tt]oken" backend/
# Look for middleware that might handle authentication
rg -A 5 "auth.*middleware" backend/
Length of output: 2558
|
||
router.post("/create",authenticateCustomer, createEvent); | ||
router.get("/all",authenticateCustomer, getEvents); | ||
router.get("/delete",authenticateCustomer, deleteEvent); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use DELETE HTTP method for delete operations.
Using GET for delete operations violates REST principles and could lead to unintended consequences (e.g., search engine crawlers accidentally deleting resources). Consider changing to DELETE method.
-router.get("/delete", authenticateCustomer, deleteEvent);
+router.delete("/delete", authenticateCustomer, deleteEvent);
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
router.get("/delete",authenticateCustomer, deleteEvent); | |
router.delete("/delete",authenticateCustomer, deleteEvent); |
router.post("/create",authenticateCustomer, createEvent); | ||
router.get("/all",authenticateCustomer, getEvents); | ||
router.get("/delete",authenticateCustomer, deleteEvent); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Authentication should not be required for GET /all endpoint
The Event.jsx component shows that event listings are meant to be public, with authentication only required for event registration. This is evidenced by:
- The events page is publicly accessible in the router configuration
- The frontend makes unauthenticated requests to
/api/event/all
- Only the "Register for Event" button requires authentication, redirecting to login if needed
- Event listings serve as a marketing tool showing upcoming events to all visitors
The current authentication middleware on GET /all conflicts with this design and should be removed.
🔗 Analysis chain
Verify if authentication is required for GET /all endpoint.
Based on the PR objectives to "Restrict Event Booking to Verified Users", it's unclear if viewing events should also be restricted. Consider if this aligns with the business requirements, as typically event listings are public while booking/modifications are restricted.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if there are any public-facing components that might need this event data
rg -l "getEvents|/event/all" --type js --type jsx --type ts --type tsx
Length of output: 100
Script:
#!/bin/bash
# Check for frontend components or API calls related to events listing
rg -l "getEvents|/events/all|/event/all" --type js
# Check if there are any public routes or components related to events
rg "router\.(get|post)\s*\(['\"].*event" --type js -A 2
# Look for any event-related components or pages
fd -e js -e jsx -e ts -e tsx | xargs rg "event" -i -l
Length of output: 1692
Script:
#!/bin/bash
# Check the Event.jsx component to see if it's a public-facing page
cat frontend/src/components/Pages/Event.jsx
# Check the router configuration to see how the event page is configured
cat frontend/src/router/index.jsx
# Check the event controller implementation
cat backend/controller/event.controller.js
Length of output: 14848
<button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4"> | ||
Register for Event | ||
</button> | ||
</div> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance registration button with loading and disabled states.
The button should provide visual feedback during the authentication process.
- <button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
+ <button
+ onClick={handleRegisterClick}
+ disabled={isLoading}
+ className={`
+ bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4
+ ${isLoading ? 'opacity-50 cursor-not-allowed' : 'hover:bg-[#FDE68A]'}
+ `}
+ >
+ {isLoading ? 'Verifying...' : 'Register for Event'}
</button>
Committable suggestion was skipped due to low confidence.
} | ||
|
||
req.user = user; | ||
logger.info(`Customer authenticated: ${user.name}`); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid logging personally identifiable information (PII)
Logging the customer's name may expose PII in the logs. To comply with privacy policies, consider logging less sensitive information, such as the user ID.
Modify the log statement:
-logger.info(`Customer authenticated: ${user.name}`);
+logger.info(`Customer authenticated: ${user._id}`);
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
logger.info(`Customer authenticated: ${user.name}`); | |
logger.info(`Customer authenticated: ${user._id}`); |
if (err.name === "TokenExpiredError") { | ||
return res.status(401).json({ message: "Token expired" }); | ||
} | ||
logger.error("Token verification failed:", err); | ||
return res.status(403).json({ message: "Invalid token" }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Return 401 Unauthorized for invalid tokens
Returning a 403 Forbidden
status code for an invalid token may not be appropriate. A 401 Unauthorized
status is more suitable for authentication failures due to invalid credentials.
Apply this diff to update the status code:
if (err.name === "TokenExpiredError") {
return res.status(401).json({ message: "Token expired" });
}
-logger.error("Token verification failed:", err);
-return res.status(403).json({ message: "Invalid token" });
+logger.error("Token verification failed:", err.message);
+return res.status(401).json({ message: "Invalid token" });
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if (err.name === "TokenExpiredError") { | |
return res.status(401).json({ message: "Token expired" }); | |
} | |
logger.error("Token verification failed:", err); | |
return res.status(403).json({ message: "Invalid token" }); | |
if (err.name === "TokenExpiredError") { | |
return res.status(401).json({ message: "Token expired" }); | |
} | |
logger.error("Token verification failed:", err.message); | |
return res.status(401).json({ message: "Invalid token" }); |
if (err.name === "TokenExpiredError") { | ||
return res.status(401).json({ message: "Token expired" }); | ||
} | ||
logger.error("Token verification failed:", err); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Limit error details in logs to prevent sensitive data exposure
Logging the entire error object may unintentionally expose sensitive information. Consider logging only essential error details.
Modify the log statement:
-logger.error("Token verification failed:", err);
+logger.error(`Token verification failed: ${err.message}`);
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
logger.error("Token verification failed:", err); | |
logger.error(`Token verification failed: ${err.message}`); |
const token = req.header("Authorization")?.split(" ")[1]; | ||
|
||
if (!token) { | ||
return res.status(401).json({ message: "Authorization token is missing" }); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handle malformed Authorization headers to prevent potential errors
The current implementation assumes that the Authorization
header is in the format 'Bearer <token>'
. If the header is present but not in the expected format, token
will be undefined
, and the user will receive a misleading error message.
Apply this diff to improve header parsing and provide more informative feedback:
const token = req.header("Authorization")?.split(" ")[1];
-if (!token) {
- return res.status(401).json({ message: "Authorization token is missing" });
+const authHeader = req.header("Authorization");
+if (!authHeader || !authHeader.startsWith("Bearer ")) {
+ return res.status(401).json({ message: "Invalid Authorization header format" });
+}
+const token = authHeader.split(" ")[1];
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const token = req.header("Authorization")?.split(" ")[1]; | |
if (!token) { | |
return res.status(401).json({ message: "Authorization token is missing" }); | |
} | |
const authHeader = req.header("Authorization"); | |
if (!authHeader || !authHeader.startsWith("Bearer ")) { | |
return res.status(401).json({ message: "Invalid Authorization header format" }); | |
} | |
const token = authHeader.split(" ")[1]; |
@haseebzaki-07 resolve the conflicts |
hey @RamakrushnaBiswal done! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- frontend/src/components/Pages/Event.jsx (3 hunks)
🔇 Additional comments (2)
frontend/src/components/Pages/Event.jsx (2)
198-200
: Update button text to indicate verification requirement.
The button text should indicate that verification is required to register for events, helping users understand the requirement upfront.
- <button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
- Register for Event
- </button>
+ <button onClick={handleRegisterClick} className="bg-[#FEF3C7] dark:bg-black text-gray-700 dark:text-white px-4 py-2 rounded-md mt-4">
+ Register for Event (Verified Users Only)
+ </button>
Additionally, the previous review comment about enhancing the button with loading and disabled states remains valid.
38-45
:
Authentication implementation doesn't meet verified user requirement.
The current implementation only checks for token presence but doesn't verify the user's verification status as required by the PR objectives. Additionally, using alert()
provides poor user experience.
The previous review comment for this section remains valid and provides a comprehensive solution that includes:
- Proper verification status check
- Better error handling
- Improved user notifications
- Loading states management
const handleRegisterClick = () => { | ||
const isAuthenticated = Boolean(Cookies.get('authToken')); | ||
|
||
if (!isAuthenticated) { | ||
alert("Please sign in to register for the event."); | ||
navigate('/login'); | ||
} | ||
}; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Event registration endpoint is missing in the backend
The current implementation only checks for authentication but lacks the actual event registration functionality:
- The frontend
handleRegisterClick
only verifies authentication and redirects to login - No event registration endpoint exists in
customerRouter.js
- No API calls are found for event registration in the codebase
The code needs to be updated to:
- Add an event registration endpoint in the backend
- Implement the API call in the frontend after authentication check
- Handle the registration response appropriately
🔗 Analysis chain
Verify backend endpoint for user verification.
Let's verify if the backend endpoint for user verification exists and is accessible.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the backend verification endpoint exists
# Expected: Find route definition for user verification endpoint
# Search for verification endpoint in route definitions
echo "Searching for verification endpoint..."
rg -l "verify|isVerified" --type js
# Search for middleware that checks verification status
echo "Searching for verification middleware..."
rg "isVerified" --type js -C 3
Length of output: 3390
Script:
#!/bin/bash
# Let's check the Event component and related files to understand the registration flow
# Check Event component implementation
echo "Checking Event component implementation..."
rg -A 10 "handleRegisterClick" frontend/src/components/Pages/Event.jsx
# Check if there's an API call for event registration
echo "Checking for event registration API..."
rg -l "registerForEvent|eventRegistration" --type js
# Check customer router for event registration endpoints
echo "Checking customer router..."
cat backend/routes/customerRouter.js
Length of output: 2360
@RamakrushnaBiswal please finalize these PRs |
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
fixes #427
This PR is raised again for the issues in #427
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Documentation
Chores