-
-
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
Reset Password For Play Cafe #177
Reset Password For Play Cafe #177
Conversation
…ignup/login/page
…ayCafe into reset/password
@samar12-rad 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
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: 7
🧹 Outside diff range and nitpick comments (12)
backend/routes/customerRouter.js (2)
2-6
: LGTM! Consider alphabetizing imports for better maintainability.The addition of
resetPassword
aligns with the PR objectives. The multi-line formatting improves readability.Consider alphabetizing the imported functions for easier maintenance:
const { createCustomer, loginCustomer, resetPassword, } = require("../controller/customer.controller");
15-19
: LGTM! Consider adding the new reset-password endpoint to the response.The reformatting improves readability, and the addition of a documentation URL is a good practice.
Consider adding the new reset-password endpoint to the
endpoints
object in the response:endpoints: { login: "/login", register: "/register", resetPassword: "/reset-password", },frontend/src/router/index.jsx (1)
32-34
: New routes added correctly, consider grouping related routes.The new routes for signup, login, and password reset have been added correctly, aligning with the PR objectives. To improve organization, consider grouping these related routes together in the configuration.
You could reorder the routes like this for better organization:
<Route path="/" element={<App />}> <Route index={true} path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/menu" element={<Menu />} /> <Route path="/boardgame" element={<Boardgame />} /> <Route path="/events" element={<Event />} /> <Route path="/book" element={<MyBook />} /> <Route path="/reservation" element={<Register />} /> {/* User management routes */} <Route path="/signup" element={<Signup />} /> <Route path="/login" element={<Login />} /> <Route path="/reset-password" element={<ResetPassword />} /> {/* Catch-all route */} <Route path="*" element={<NotFound />} /> </Route>This grouping improves readability and makes it easier to manage related routes in the future.
backend/controller/customer.controller.js (2)
68-91
: LGTM: Password reset function implemented correctlyThe resetPassword function is well-implemented with proper input validation, customer existence check, secure password hashing, and appropriate error handling. It aligns well with the PR objectives.
Consider adding more specific error handling:
} catch (error) { - res.status(500).json({ error: "Internal server error" }); + console.error('Error in resetPassword:', error); + res.status(500).json({ error: "An error occurred while resetting the password. Please try again later." }); }This change would log the error for debugging purposes and provide a more user-friendly error message.
Line range hint
1-97
: Overall implementation looks good, consider reducing duplicationThe addition of the resetPassword function and its integration with the existing code is well done. The consistent use of Zod for input validation and bcrypt for password hashing across all functions is commendable.
To further improve the code, consider extracting the common Zod schema and error handling logic into separate functions to reduce duplication. For example:
const baseUserSchema = z.object({ email: z.string().email("Invalid email address"), password: z.string().min(6, "Password must be at least 6 characters long"), }); function validateRequest(schema, body) { const validation = schema.safeParse(body); if (!validation.success) { return { error: validation.error.errors }; } return null; } function handleServerError(res, error) { console.error('Server error:', error); res.status(500).json({ error: "An error occurred. Please try again later." }); }These utility functions could then be used in each of the main functions to streamline the code and make it more maintainable.
frontend/src/components/Pages/Signup.jsx (2)
1-4
: Consider adding PropTypes for better type checking and documentation.While the current implementation is functional, adding PropTypes can improve code quality and maintainability. It helps catch errors early and serves as documentation for the component's interface.
To implement this, first import PropTypes:
import PropTypes from 'prop-types';Then, at the end of the file, add:
Signup.propTypes = { // Add any props here if needed in the future };
65-69
: Use type="submit" for the submit button.For better semantics and accessibility, it's recommended to use
type="submit"
on the submit button within a form, rather than handling the submission via anonClick
event.Here's the suggested change:
<button type="submit" className="button-confirm mx-auto mt-12 px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]" > Let's go → </button>Then, update your form tag to handle the submission:
<form onSubmit={handleSubmit} className="form z-10 p-16 bg-lightblue flex flex-col items-start justify-center gap-5 rounded-lg border-2 border-black shadow-[4px_4px_0px_0px_black] bg-[#f1e9dc]">This change ensures that the form can be submitted by pressing Enter on any input field, improving accessibility.
frontend/src/components/Pages/Login.jsx (1)
7-17
: LGTM: State management is well-implemented.The use of
useState
for form data, loading state, and error handling is appropriate. ThehandleChange
function correctly updates the state while maintaining immutability.Consider adding prop-types or TypeScript for better type checking and documentation of the component's props and state.
frontend/src/components/Shared/Navbar.jsx (3)
47-53
: LGTM: Improved readability of ternary operations.The reformatting of the ternary operations for
hoverTextColorClass
andmobileMenuBaseTextColorClass
enhances code readability without altering the logic. This is a good practice for maintaining clean code.Consider using template literals for better readability:
const hoverTextColorClass = `hover:text-gray-${isScrolled ? '900' : '800'}`; const mobileMenuBaseTextColorClass = `text-gray-${isScrolled ? '900' : '800'}`;
79-82
: LGTM: Improved desktop menu items and login functionality.The reformatting of the
li
element enhances code readability. The login button now correctly uses thenavigate
function for routing, which aligns with the PR objectives of implementing new login functionality.Consider updating the logout button to use
navigate
as well for consistency:onClick={() => { setisloggedIn(false); navigate('/'); // or navigate to appropriate page after logout }}Also applies to: 93-95, 101-103
155-159
: LGTM: Improved mobile menu items and login functionality.The reformatting of the
div
element enhances code readability. The login button in the mobile menu now correctly uses thenavigate
function for routing, which is consistent with the desktop version and aligns with the PR objectives.Consider updating the logout button in the mobile menu to use
navigate
as well for consistency:onClick={() => { setisloggedIn(false); navigate('/'); // or navigate to appropriate page after logout }}Also applies to: 182-182
README.md (1)
223-224
: Replace hard tabs with spaces for consistent formatting.To ensure consistent formatting across different editors and platforms, it's recommended to use spaces instead of hard tabs for indentation in Markdown files.
Replace the hard tabs on lines 223 and 224 with the appropriate number of spaces to maintain the current indentation level.
🧰 Tools
🪛 Markdownlint
223-223: Column: 1
Hard tabs(MD010, no-hard-tabs)
224-224: Column: 1
Hard tabs(MD010, no-hard-tabs)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (1)
frontend/src/assets/login.png
is excluded by!**/*.png
📒 Files selected for processing (8)
- README.md (1 hunks)
- backend/controller/customer.controller.js (2 hunks)
- backend/routes/customerRouter.js (1 hunks)
- frontend/src/components/Pages/Login.jsx (1 hunks)
- frontend/src/components/Pages/ResetPassword.jsx (1 hunks)
- frontend/src/components/Pages/Signup.jsx (1 hunks)
- frontend/src/components/Shared/Navbar.jsx (8 hunks)
- frontend/src/router/index.jsx (1 hunks)
🧰 Additional context used
🪛 Markdownlint
README.md
223-223: Column: 1
Hard tabs(MD010, no-hard-tabs)
224-224: Column: 1
Hard tabs(MD010, no-hard-tabs)
🔇 Additional comments (20)
backend/routes/customerRouter.js (2)
1-26
: Overall, the changes look good and align with the PR objectives.The addition of the password reset functionality enhances the user management capabilities of the API. The code is well-structured and consistent with existing patterns. The minor suggestions provided (alphabetizing imports and updating the root response) will further improve maintainability and completeness.
24-24
: LGTM! Verify the implementation of the resetPassword function.The new route for password reset is correctly set up and aligns with the PR objectives.
To ensure the
resetPassword
function is properly implemented, please run the following script:✅ Verification successful
Verified: resetPassword Function Implementation
resetPassword
function is properly defined.- Handles potential errors using
try/catch
blocks.- Sends appropriate responses with
res.status(...)
andres.json(...)
.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the implementation of the resetPassword function # Test: Search for the resetPassword function definition ast-grep --lang javascript --pattern 'const resetPassword = $_' # Test: Check if the function handles potential errors rg --type javascript 'function resetPassword' -A 10 | rg 'try|catch' # Test: Verify if the function sends a response rg --type javascript 'function resetPassword' -A 20 | rg 'res\.(?:json|send|status)'Length of output: 293
Script:
#!/bin/bash # Description: Verify the implementation of the resetPassword function # Test: Search for the resetPassword function definition ast-grep --lang js --pattern 'const resetPassword = $_' # Test: Check if the function handles potential errors rg --type js 'function resetPassword' -A 10 | rg 'try|catch' # Test: Verify if the function sends a response rg --type js 'function resetPassword' -A 20 | rg 'res\.(?:json|send|status)'Length of output: 513
frontend/src/router/index.jsx (3)
3-19
: LGTM: Import statements are properly updated.The import statements have been reformatted for consistency, and new components (Signup, Login, ResetPassword) have been correctly imported. These changes align with the PR objectives of adding new user management features.
22-36
: LGTM: Router configuration is properly structured.The router configuration maintains its structure while incorporating the new routes. The use of
createBrowserRouter
andcreateRoutesFromElements
follows React Router best practices, ensuring a clean and maintainable routing setup.
Line range hint
1-40
: Overall LGTM, suggest verifying component implementations.The changes to the router configuration are well-implemented and align with the PR objectives. The new routes for user management (signup, login, and password reset) have been correctly added.
To ensure complete functionality, it would be beneficial to verify the implementation of the Signup, Login, and ResetPassword components. You can use the following script to check for the existence and basic structure of these components:
This script will help ensure that the new components exist and have a basic React component structure.
backend/controller/customer.controller.js (2)
20-23
: LGTM: Email uniqueness check addedThe addition of an email uniqueness check is a good practice. It prevents duplicate registrations and provides a clear error message to the user.
95-97
: LGTM: Module exports updated correctlyThe module exports have been correctly updated to include the new resetPassword function, making it accessible to other parts of the application.
frontend/src/components/Pages/Signup.jsx (1)
75-75
: LGTM: Component export is correct.The default export of the Signup component is implemented correctly.
frontend/src/components/Pages/Login.jsx (3)
1-6
: LGTM: Imports and component setup look good.The imports are appropriate, and using an environment variable for the API URL is a good practice for configuration management.
91-91
: LGTM: Component export is correct.The default export of the Login component is appropriate and follows React best practices.
1-91
: Overall, good implementation with room for improvement.The Login component is well-structured and implements the basic functionality correctly. However, there are several areas where it can be improved:
- Enhance error handling and success case management in the
handleSubmit
function.- Implement better user feedback for loading and error states.
- Improve accessibility with proper labeling and ARIA attributes.
- Consider adding prop-types or TypeScript for better type checking.
These improvements will enhance the user experience, make the component more robust, and improve its maintainability.
frontend/src/components/Pages/ResetPassword.jsx (2)
1-7
: LGTM: Imports and component declaration are appropriate.The imports and component declaration are well-structured and follow React best practices. The use of hooks like useState and useNavigate is appropriate for the component's functionality.
118-118
: LGTM: Component export is correct.The default export of the ResetPassword component follows React best practices and allows for easy import in other parts of the application.
frontend/src/components/Shared/Navbar.jsx (6)
3-3
: LGTM: Import statement updated correctly.The addition of
useNavigate
to the import statement is appropriate and consistent with its usage in the component. This change supports the new navigation functionality implemented in the component.
10-10
: LGTM: useNavigate hook initialized correctly.The
useNavigate
hook is properly initialized, enabling programmatic navigation within the component. This addition aligns with the changes made to the login and signup functionality.
59-61
: LGTM: Improved readability of nav element's className.The reformatting of the
className
string in the nav element enhances code readability without altering the functionality. This change is consistent with the overall improvements in code clarity throughout the file.
67-71
: LGTM: Improved readability of img element.The reformatting of the
img
element, with attributes spread across multiple lines, enhances code readability. This change is consistent with the overall improvements in code clarity throughout the file.
113-116
: LGTM: Improved readability of mobile menu button.The reformatting of the button and SVG elements in the mobile menu button enhances code readability without altering functionality. This change is consistent with the overall improvements in code clarity throughout the file.
Also applies to: 125-130, 140-145
Line range hint
1-194
: Overall assessment: Well-implemented changes with improved readability.The changes in this file successfully implement the new navigation functionality for login and improve overall code readability. The reformatting of various elements enhances code clarity without altering core functionality. The use of
useNavigate
for routing is consistent with modern React practices.A few minor suggestions have been made for further improvements:
- Consider using template literals for some class names to enhance readability.
- Update the logout functionality to use
navigate
for consistency with the login functionality.These changes align well with the PR objectives and contribute to a more maintainable codebase.
README.md (1)
216-222
: LGTM! Verify the removal of a contributor.The addition of Jay Shah and the repositioning of Mohit Rana in the contributors list look good. However, please confirm if the removal of Bashua Mutiat from the list was intentional.
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: 6
🧹 Outside diff range and nitpick comments (6)
frontend/src/components/Pages/Login.jsx (1)
76-89
: LGTM: Form elements and submit button are well-implemented.The additional form elements, including the signup link, error message display, and submit button, are implemented correctly. The loading state indication in the submit button is a good user experience feature.
One minor suggestion for improvement:
Consider adding more prominence to the error message for better visibility:
{error && ( <p className="text-red-500 mt-2 p-2 border border-red-500 rounded bg-red-100"> {error} </p> )}This change will make the error message more noticeable to users.
frontend/src/components/Pages/Signup.jsx (4)
1-13
: LGTM! Consider using a custom hook for form management.The imports, component structure, and state management look good. To improve reusability and separate concerns, consider creating a custom hook for form management. This could be especially useful if you have multiple forms in your application.
// useForm.js import { useState } from 'react'; const useForm = (initialState) => { const [data, setData] = useState(initialState); const handleChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; return [data, handleChange, setData]; }; // In your component const [formData, handleChange, setFormData] = useForm({ name: "", email: "", password: "", });
72-75
: LGTM! Consider enhancing accessibility with semantic HTML.The form structure and styling look good. To improve accessibility, consider wrapping the form content in a
<main>
tag and adding anaria-label
to the form:<main className="w-screen h-screen flex items-center justify-center pt-10"> <img src={photo} alt="login" className="w-3/4 absolute" /> <form className="form z-10 p-16 bg-lightblue flex flex-col items-start justify-center gap-5 rounded-lg border-2 border-black shadow-[4px_4px_0px_0px_black] bg-[#f1e9dc]" aria-label="Sign up form" > {/* form content */} </form> </main>
76-82
: LGTM! Enhance accessibility with semantic HTML.The form title structure is clear and well-styled. To improve accessibility, consider using semantic HTML elements:
<header className="title text-[#323232] font-black text-7xl mb-6"> <h1> Play Cafe, <span className="block text-[#666] font-semibold text-2xl"> Register to continue </span> </h1> </header>This change provides better structure for screen readers and improves the overall semantics of your document.
107-123
: LGTM! Consider enhancing error message accessibility.The error display and submit button implementation look good. The loading state on the button provides good user feedback. To improve accessibility for the error message, consider adding an
aria-live
attribute:{error && ( <div className="w-full p-2 bg-red-100 text-red-700 border border-red-400 rounded-md" aria-live="polite" > {error} </div> )}This change ensures that screen readers will announce the error message when it appears.
frontend/src/components/Pages/ResetPassword.jsx (1)
22-25
: Consider using a more robust email validation regex.The current email validation regex is basic and might not cover all valid email formats. Consider using a more comprehensive regex or a dedicated email validation library to ensure better coverage of valid email formats.
Here's an example of a more robust email regex:
const isValidEmail = (email) => { const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/; return emailRegex.test(email); };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
- backend/package.json (1 hunks)
- frontend/src/components/Pages/Login.jsx (1 hunks)
- frontend/src/components/Pages/ResetPassword.jsx (1 hunks)
- frontend/src/components/Pages/Signup.jsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (7)
backend/package.json (1)
19-19
: LGTM: Addition of jsonwebtoken packageThe addition of the
jsonwebtoken
package (version ^9.0.2) is appropriate for implementing the new password reset functionality mentioned in the PR objectives. JWT is a secure method for handling authentication and authorization processes.To ensure best practices are followed when implementing JWT for password reset, please verify the following:
- Token expiration: Ensure that reset tokens have a short expiration time.
- Token storage: Avoid storing tokens in localStorage; use secure, httpOnly cookies instead.
- HTTPS: Confirm that all communication involving JWTs is over HTTPS.
- Secret key: Verify that a strong, unique secret key is used for signing JWTs.
Run the following script to check for proper JWT usage:
frontend/src/components/Pages/Login.jsx (2)
1-17
: LGTM: Imports and component initialization are well-structured.The imports, API URL setup, and state initialization are correctly implemented. Using an environment variable for the API URL with a fallback is a good practice for flexibility across different environments.
94-94
: LGTM: Component export is correct.The Login component is properly exported as the default export.
frontend/src/components/Pages/Signup.jsx (1)
15-17
: LGTM! handleChange function is well-implemented.The
handleChange
function is correctly implemented to update the form state based on input changes. It properly uses the spread operator to maintain existing state while updating the changed field.frontend/src/components/Pages/ResetPassword.jsx (3)
1-20
: Imports and component initialization look good.The necessary imports, state initialization, and API URL configuration are well-structured and follow best practices. The use of environment variables for the API URL is particularly commendable for maintaining flexibility across different environments.
73-93
: Form structure and error handling look good.The form is well-structured with appropriate CSS classes, and the error message display is implemented correctly. This provides a good user experience for form interaction and error feedback.
118-137
: Form submission and component export look good.The submit button is well-implemented with proper handling of the loading state, providing good user feedback during form submission. The component is correctly exported for use in other parts of the application.
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
🧹 Outside diff range and nitpick comments (4)
frontend/src/components/Pages/Login.jsx (2)
20-44
: Good improvements, consider further enhancements.The
handleSubmit
function has been improved as per previous suggestions. It now includes proper error handling, loading state management, and success navigation. However, there are still some areas for improvement:
- Consider implementing token storage upon successful login.
- Add input validation before making the API call to improve user experience and reduce unnecessary server requests.
Here's a suggested enhancement:
const handleSubmit = async (e) => { e.preventDefault(); setIsLoading(true); setError(null); // Basic input validation if (!data.email || !data.password) { setError("Please fill in all fields"); setIsLoading(false); return; } try { const response = await fetch(`${API_URL}/api/user/login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); const result = await response.json(); if (!response.ok) { throw new Error(result.message || "Login failed"); } // Store the token in localStorage or a more secure storage method localStorage.setItem('token', result.token); message.success("Login successful"); navigate("/"); } catch (err) { setError(err.message || "An error occurred. Please try again."); } finally { setIsLoading(false); } };This implementation adds basic input validation and includes token storage upon successful login.
46-89
: Enhance form accessibility.The form structure and styling are well-implemented, including error display and loading state handling. However, to improve accessibility, consider the following enhancements:
- Add labels for input fields (you can use visually hidden labels if you want to maintain the current design).
- Include ARIA attributes for better screen reader support.
- Add autocomplete attributes to help users fill the form more easily.
Here's a suggested improvement for the email input (apply similar changes to the password input):
<div className="relative"> <label htmlFor="email" className="sr-only">Email</label> <input id="email" className="input w-full h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[15px] font-semibold text-[#323232] p-2.5 focus:outline-none focus:border-[#2d8cf0] placeholder-[#666] placeholder-opacity-80" name="email" placeholder="Email" type="email" onChange={(e) => handleChange(e)} required aria-required="true" autoComplete="email" /> </div>These changes will significantly improve the accessibility of your form while maintaining its current visual design.
frontend/src/components/Pages/Signup.jsx (2)
20-71
: Improved form submission with validation, but consider enhancing error handling and user feedback.Great job on implementing comprehensive input validation and error handling. The use of async/await for the API call is appropriate. However, consider the following improvements:
- Use more specific error types or a custom error handler to provide more detailed feedback.
- Replace the alert with a more user-friendly success message, perhaps using a toast notification or a success state in the component.
Example of a more specific error handler:
const handleApiError = (error) => { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx setError(`Server error: ${error.response.data.message}`); } else if (error.request) { // The request was made but no response was received setError('No response from server. Please try again later.'); } else { // Something happened in setting up the request that triggered an Error setError('An unexpected error occurred. Please try again.'); } }; // In the catch block: catch (error) { handleApiError(error); console.error("Error:", error); }
108-119
: Good error display and submit button implementation.The error display and submit button are well-implemented. The loading state feedback is a nice touch. Consider a minor improvement to the button's onClick handler for better reusability:
<button className="..." type="submit" > {isLoading ? "Loading..." : "Let's go →"} </button>Then, attach the handleSubmit function to the form's onSubmit event:
<form onSubmit={handleSubmit} className="..."> {/* ... form contents ... */} </form>This approach allows the form to be submitted by pressing Enter in any input field, improving accessibility and user experience.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- frontend/src/components/Pages/Login.jsx (1 hunks)
- frontend/src/components/Pages/ResetPassword.jsx (1 hunks)
- frontend/src/components/Pages/Signup.jsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- frontend/src/components/Pages/ResetPassword.jsx
🧰 Additional context used
🔇 Additional comments (8)
frontend/src/components/Pages/Login.jsx (4)
1-11
: LGTM: Imports and component initialization look good.The necessary modules are imported, and the component is initialized correctly. The use of environment variables for the API URL with a fallback is a good practice.
13-18
: LGTM: Form handling and state management are well implemented.The
handleChange
function correctly updates the state, and the additional states for navigation, loading, and error handling are properly set up. This provides a good foundation for user interaction and feedback.
94-94
: LGTM: Component export is correct.The Login component is properly exported as the default export, following React conventions.
1-94
: Overall, good implementation with room for improvement.The Login component is well-structured and implements the necessary functionality for user authentication. Key strengths include:
- Proper state management and form handling.
- API interaction with error handling.
- User feedback through loading states and error messages.
Main areas for improvement:
- Enhance form accessibility with labels and ARIA attributes.
- Implement client-side input validation before form submission.
- Add token storage upon successful login.
These enhancements will improve the user experience, accessibility, and overall robustness of the login functionality.
frontend/src/components/Pages/Signup.jsx (4)
1-14
: Good use of environment variables and state management.The component setup looks good. I appreciate the use of an environment variable for the API URL, which addresses a previous suggestion. The state management is well-structured, including form data, loading state, and error handling.
16-18
: Effective form data update implementation.The
handleChange
function is concise and correctly updates the form data state using the spread operator.
73-83
: Well-structured and styled form layout.The form structure and styling look good. The use of Tailwind classes provides a consistent and appealing design.
121-124
: Correct component export.The Signup component is properly exported as the default export.
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: 0
🧹 Outside diff range and nitpick comments (3)
frontend/src/components/Pages/Signup.jsx (3)
16-71
: Improved form handling with room for further enhancement.Great job on implementing comprehensive input validation and error handling. This addresses several past comments. However, consider the following improvements:
The
handleSubmit
function is quite long. Consider breaking it down into smaller, more manageable functions (e.g.,validateForm
,submitForm
).In the catch block, consider providing more specific error messages based on the error type.
Consider using a library like Axios for HTTP requests, which provides better error handling and request/response interceptors.
Here's a suggestion for breaking down the
handleSubmit
function:const validateForm = () => { if (!data.email || !data.password || !data.name) { return "Please fill in all fields"; } if (data.password.length < 8) { return "Password must be at least 8 characters long"; } if (data.name.length < 3) { return "Name must be at least 3 characters long"; } if (!data.email.includes("@")) { return "Please enter a valid email address"; } return null; }; const submitForm = async () => { const response = await fetch(`${API_URL}/api/user/register`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); const result = await response.json(); if (!response.ok) { throw new Error(result.error); } return result; }; const handleSubmit = async (e) => { e.preventDefault(); setIsLoading(true); setError(null); const validationError = validateForm(); if (validationError) { setError(validationError); setIsLoading(false); return; } try { await submitForm(); alert("Registered successfully! Please log in."); navigate("/"); } catch (error) { setError(error.message); console.error("Error:", error); } finally { setIsLoading(false); } };
84-110
: Enhance form inputs for better accessibility and security.While the inputs are well-styled and include some accessibility attributes, there are a few improvements we can make:
- Add text content to the labels for better screen reader support:
<label htmlFor="name" className="sr-only">Name</label>
- For the password input, add a pattern attribute to enforce a password policy:
<input // ... other attributes pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number, one uppercase and lowercase letter, and at least 8 characters" />
- Consider adding
aria-describedby
attributes to link inputs with error messages for better accessibility.Apply these changes to all input fields as appropriate.
111-127
: Well-implemented error handling and submit button.The error display and submit button implementation look good. The conditional rendering of error messages and the loading state in the button provide excellent user feedback.
One small suggestion for improvement:
Consider adding a disabled state to the button when the form is submitting to prevent multiple submissions:
<button className="button-confirm mx-auto mt-12 px-4 w-30 h-10 rounded-md border-2 border-black bg-beige shadow-[4px_4px_0px_0px_black] text-[17px] font-semibold text-[#323232] cursor-pointer active:shadow-none active:translate-x-[3px] active:translate-y-[3px]" onClick={(e) => handleSubmit(e)} disabled={isLoading} > {isLoading ? "Loading..." : "Let's go →"} </button>
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- frontend/src/components/Pages/Signup.jsx (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
frontend/src/components/Pages/Signup.jsx (2)
1-14
: Good use of environment variables and React best practices.The component initialization looks good. I appreciate the use of an environment variable for the API URL, which addresses a previous suggestion. The state management using React hooks is well-structured.
73-83
: Well-structured and styled form layout.The form structure and styling look great. The use of Tailwind CSS classes provides a responsive and visually appealing interface. The inclusion of a background image and clear title/subtitle enhances the user experience.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
180babd
into
RamakrushnaBiswal:main
Created backend routes for reset password
Create function in backend to resset password and successfull message on resset successfull
On frontend-
Created resset page
Created form
Integrated with backend
Tested the code
For issue #145
Summary by CodeRabbit
Release Notes
New Features
Signup
), login (Login
), and password reset (ResetPassword
).Updates
Improvements