Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@Saahi30
Copy link
Collaborator

@Saahi30 Saahi30 commented Jun 4, 2025

πŸ“ Description

Makes the password reset flow fully functional using Supabase Auth and improves the signup experience by allowing users to select their own username, with a uniqueness check against the users table.

πŸ”§ Changes Made

  • Made the password reset flow fully functional using Supabase Auth, including proper session handling and user feedback.
  • Added username selection to the signup form, with a uniqueness check against the users table.

βœ… Checklist

  • [βœ… ] I have read the contributing guidelines.

Summary by CodeRabbit

  • New Features

    • Signup form now requires a unique username and validates its availability before account creation.
    • Forgot Password page checks if an email exists and prompts users to sign up if not found.
  • Improvements

    • Password reset flow uses Supabase's secure API, with improved error messages and a progress bar redirect after success.
    • Enhanced error handling and user feedback throughout authentication flows.
    • Prevents unwanted redirects during password recovery.
  • Chores

    • Removed the backend environment variable example file.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 4, 2025

Warning

Rate limit exceeded

@Saahi30 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 40 seconds before requesting another review.

βŒ› How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 795ae23 and 34e7fa0.

πŸ“’ Files selected for processing (1)
  • Backend/.env-example (1 hunks)

Walkthrough

The changes update authentication flows in the frontend by improving password reset and signup logic, adding username checks, and refining navigation after authentication events. The backend's example environment file is removed. The password reset and signup pages now interact more robustly with Supabase, including user existence and username uniqueness checks.

Changes

File(s) Change Summary
Backend/.env-example Removed the example environment variables file.
Backend/app/models/models.py Restored non-nullable password_hash column with comment in User model.
Backend/app/routes/post.py Removed trailing whitespace in dictionary key for password_hash in create_user function.
Frontend/src/context/AuthContext.tsx Added useLocation; conditional navigation after auth state changes to avoid redirect during password recovery.
Frontend/src/pages/ForgotPassword.tsx Checks if email exists before sending reset email; adds signup prompt; improves error handling and UI.
Frontend/src/pages/ResetPassword.tsx Uses Supabase password update API directly; adds progress bar countdown; improved error handling and UI; redirects to dashboard after reset.
Frontend/src/pages/Signup.tsx Added username field with validation; checks username uniqueness; inserts user record in "users" table; updates navigation post-signup.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ForgotPasswordPage
    participant Supabase

    User->>ForgotPasswordPage: Submit email for password reset
    ForgotPasswordPage->>Supabase: Query "users" table for email
    alt Email exists
        ForgotPasswordPage->>Supabase: Call resetPasswordForEmail
        Supabase-->>ForgotPasswordPage: Success/Error
        ForgotPasswordPage-->>User: Show result or error
    else Email does not exist
        ForgotPasswordPage-->>User: Show signup prompt
    end
Loading
sequenceDiagram
    participant User
    participant SignupPage
    participant Supabase

    User->>SignupPage: Submit signup form (with username)
    SignupPage->>Supabase: Query "users" table for username
    alt Username exists
        SignupPage-->>User: Show username taken error
    else Username available
        SignupPage->>Supabase: Create user via auth
        SignupPage->>Supabase: Insert user record in "users" table
        Supabase-->>SignupPage: Success/Error
        SignupPage-->>User: Navigate or show error
    end
Loading
sequenceDiagram
    participant User
    participant ResetPasswordPage
    participant Supabase

    User->>ResetPasswordPage: Submit new password
    ResetPasswordPage->>Supabase: Update password via API
    alt Success
        ResetPasswordPage-->>User: Show success, start countdown
        ResetPasswordPage->>User: Redirect to dashboard
    else Error
        ResetPasswordPage-->>User: Show error message
    end
Loading

Poem

In the warren of code, new tunnels appear,
Passwords reset with a hop, never fear!
Usernames checked before bunnies sign in,
No more surprise redirects when you begin.
The .env is gone, but the garden still growsβ€”
With each clever tweak, our security shows!
πŸ‡βœ¨


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.

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hello @Saahi30, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

Gemini here, providing a summary for this pull request. This PR significantly enhances the user authentication experience by implementing a fully functional password reset flow using Supabase Auth and improving the signup process by allowing users to select a unique username. The changes involve updating the authentication context, creating dedicated pages for forgot password and reset password, and modifying the signup form and logic.

Highlights

  • Password Reset Flow: Implemented the complete password reset flow using Supabase Auth, including sending reset emails and handling the password update on the reset page.
  • Username Selection on Signup: Added a username field to the signup form and implemented a uniqueness check against the database to ensure each user has a distinct username.
  • Supabase Integration: Leveraged Supabase Auth features for both password reset and user creation, including handling sessions and user data insertion.
  • Improved User Feedback: Added error handling and success messages for both the forgot password and reset password pages, including a redirect timer on successful password reset.

Changelog

Click here to see the changelog
  • Frontend/src/context/AuthContext.tsx
    • Imported useLocation hook (line 8).
    • Added location state using useLocation (line 28).
    • Modified onAuthStateChange listener to prevent automatic navigation to /dashboard if the user is on the /reset-password page or the event is PASSWORD_RECOVERY (lines 38-42).
    • Updated the dependency array for the useEffect hook to include location.pathname and navigate (line 49).
  • Frontend/src/pages/ForgotPassword.tsx
    • Imported supabase utility (line 4).
    • Added showSignupPrompt state to manage displaying a prompt if the email is not found (line 11).
    • Modified handleSubmit to check for email existence in the users table before initiating the password reset flow (lines 21-31).
    • If email is not found, set showSignupPrompt to true and return (lines 27-30).
    • Called supabase.auth.resetPasswordForEmail with a redirectTo URL pointing to /reset-password (lines 32-34).
    • Updated error handling to catch and display specific Supabase errors (line 38).
    • Added conditional rendering for the signup prompt message below the error message (lines 108-112).
    • Updated the email input placeholder to mention case sensitivity (line 129).
  • Frontend/src/pages/ResetPassword.tsx
    • Imported useEffect and useRef hooks (line 1).
    • Imported supabase utility (line 5).
    • Removed placeholder token variable (line 10).
    • Added progress state and progressRef for the redirect timer animation (lines 17-18).
    • Added a useEffect hook to handle the redirect timer and progress bar animation after a successful password reset (lines 25-42).
    • Modified handleSubmit to call supabase.auth.updateUser with the new password (line 56).
    • Updated error handling to catch and display specific Supabase errors (line 60).
    • Changed the conditional rendering logic to show the success message and progress bar when isSuccess is true (line 92).
    • Updated the success message UI to display 'Password Changed Successfully' and the redirecting message with the progress bar (lines 109-120).
    • Removed the 'Invalid or Expired Link' state and UI.
  • Frontend/src/pages/Signup.tsx
    • Added username field to the formData state (line 13).
    • Modified handleSubmit to extract the username from formData (line 45).
    • Implemented a check for username uniqueness in the users table before attempting to sign up (lines 47-57).
    • If the username exists, set an error message and return (lines 53-56).
    • Updated the user insertion logic to insert into the users table instead of profiles (lines 73-89).
    • Included username, email, password_hash (as a placeholder), role, and other default fields in the users table insertion (lines 79-88).
    • Changed the navigation path after successful signup to /BasicDetails/${accountType} (line 98).
    • Added a new input field for 'Username' in the signup form UI (lines 197-214).
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with πŸ‘ and πŸ‘Ž on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


Password reset flow,
New username, unique glow,
Auth is now complete.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly improves the authentication flow by making password reset functional and enhancing the signup process with username selection and uniqueness checks. The integration with Supabase Auth for these features is well-handled in most parts.

I've identified a few areas for improvement, particularly concerning data handling in the users table during signup, and case sensitivity for emails and usernames, which could impact user experience and data integrity. Addressing these points will further strengthen the implementation.

No specific style guide was provided, so my review is based on common TypeScript/React best practices and general code clarity.

Summary of Findings

  • Data Handling in users Table (Signup): A critical issue was found regarding the insertion of a password_hash placeholder and potentially non-canonical email into the public users table during signup. This could pose security risks and lead to data inconsistencies.
  • Case Sensitivity for Email (Forgot Password): The email lookup during the password reset flow might not align with Supabase Auth's typical case-insensitive email handling, potentially affecting UX. Suggests using toLowerCase().
  • Case Sensitivity for Username (Signup): The username uniqueness check is case-sensitive. It's recommended to consider case-insensitive handling for better user experience and to prevent duplicate-but-differently-cased usernames.

Merge Readiness

The pull request introduces valuable functionality for password reset and username selection. However, there is a critical issue concerning data storage in the users table during signup (specifically the password_hash field) that must be addressed before merging. Additionally, there are medium-severity suggestions regarding email and username case sensitivity that would improve the robustness and user experience of these features.

I recommend that these changes, especially the critical one, be made and reviewed again. I am not authorized to approve pull requests, so please ensure further review and approval from authorized team members after addressing the feedback.

Comment on lines 24 to 32
.eq("email", email)
.maybeSingle();
if (userError) throw userError;
if (!users) {
setShowSignupPrompt(true);
setIsLoading(false);
return;
}
const { error } = await supabase.auth.resetPasswordForEmail(email, {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Regarding the email lookup in the users table and the subsequent call to resetPasswordForEmail:

  1. Case Sensitivity: Supabase Auth typically normalizes emails to lowercase. If your users table stores emails as they are entered, or if you want to ensure case-insensitive lookup matching Supabase's behavior, it's advisable to convert the input email to lowercase before querying and before passing to resetPasswordForEmail. This would be .eq("email", email.toLowerCase()) and supabase.auth.resetPasswordForEmail(email.toLowerCase(), ...).
  2. Placeholder Text: The current placeholder [email protected] (CASE sensitive) (line 129) could be confusing if Supabase Auth itself handles emails case-insensitively. Aligning the logic (e.g., by using toLowerCase()) would make the UX more consistent.

Could you clarify if emails are stored/handled case-sensitively throughout, or if normalizing to lowercase here would be more appropriate?

const { data: existingUser, error: userCheckError } = await supabase
.from("users")
.select("id")
.eq("username", username)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For the username uniqueness check, you're using .eq("username", username). Similar to emails, have you considered whether usernames should be case-sensitive or case-insensitive for uniqueness?

If usernames should be unique regardless of case (e.g., "User1" is the same as "user1"), you might want to:

  1. Query using a case-insensitive comparison (e.g., username.toLowerCase() if you store all usernames in lowercase, or use a database function like LOWER()).
  2. Store the username in a canonical format (e.g., all lowercase) in the users table.

This can prevent user confusion and duplicate-but-differently-cased usernames. What are your thoughts on handling username case sensitivity here?

        .eq("username", username.toLowerCase())

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
Frontend/src/pages/ResetPassword.tsx (1)

25-42: Consider extracting magic numbers and adding session validation.

The progress calculation uses magic numbers that could be clearer, and there's no validation that the user has a valid session.

+ const REDIRECT_DELAY_SECONDS = 3;
+ const PROGRESS_INTERVAL_MS = 100;

  useEffect(() => {
    if (isSuccess) {
      setProgress(0);
      progressRef.current = setInterval(() => {
        setProgress((prev) => {
          if (prev >= 100) {
            if (progressRef.current) clearInterval(progressRef.current);
            router("/dashboard");
            return 100;
          }
-         return prev + (100 / 30); // 3 seconds, 100ms interval
+         return prev + (100 / (REDIRECT_DELAY_SECONDS * 1000 / PROGRESS_INTERVAL_MS));
        });
-     }, 100);
+     }, PROGRESS_INTERVAL_MS);
    }

Also consider adding session validation:

useEffect(() => {
  // Verify user has valid session for password reset
  supabase.auth.getSession().then(({ data }) => {
    if (!data.session) {
      setError("Invalid or expired reset link. Please request a new one.");
    }
  });
}, []);
Frontend/src/pages/ForgotPassword.tsx (1)

129-129: Consider removing "CASE sensitive" from email placeholder.

Most email systems and Supabase are case-insensitive for email addresses. The "CASE sensitive" note might confuse users unnecessarily.

-                        placeholder="[email protected] (CASE sensitive)"
+                        placeholder="[email protected]"
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 5690da4 and e3d9346.

πŸ“’ Files selected for processing (5)
  • Backend/.env-example (0 hunks)
  • Frontend/src/context/AuthContext.tsx (3 hunks)
  • Frontend/src/pages/ForgotPassword.tsx (3 hunks)
  • Frontend/src/pages/ResetPassword.tsx (5 hunks)
  • Frontend/src/pages/Signup.tsx (4 hunks)
πŸ’€ Files with no reviewable changes (1)
  • Backend/.env-example
🧰 Additional context used
🧬 Code Graph Analysis (3)
Frontend/src/pages/ForgotPassword.tsx (1)
Frontend/src/utils/supabase.tsx (1)
  • supabase (6-6)
Frontend/src/pages/Signup.tsx (1)
Frontend/src/utils/supabase.tsx (1)
  • supabase (6-6)
Frontend/src/pages/ResetPassword.tsx (1)
Frontend/src/utils/supabase.tsx (1)
  • supabase (6-6)
πŸ”‡ Additional comments (8)
Frontend/src/context/AuthContext.tsx (1)

8-8: LGTM! Proper navigation handling during password reset.

The addition of useLocation and conditional navigation logic correctly prevents unwanted redirects to the dashboard during password recovery flows. This ensures users stay on the reset password page when they should.

Also applies to: 28-28, 38-44, 49-49

Frontend/src/pages/Signup.tsx (1)

47-57:

❓ Verification inconclusive

Consider race condition in username validation.

There's a potential race condition where two users could check the same username simultaneously and both proceed to create accounts. Consider using a database constraint or transaction to handle this atomically.


🏁 Script executed:

#!/bin/bash
# Check if there are any unique constraints on the users table username column
ast-grep --pattern 'CREATE TABLE users' || echo "Database schema not found in codebase"
rg -A 10 -B 5 "username.*unique\|unique.*username" || echo "No unique constraint patterns found"

Length of output: 175


Ensure username uniqueness at the database level

I didn’t find any SQL schema or migration in the repo that enforces a UNIQUE constraint on users.username. Relying solely on the client-side check still leaves a race condition where two sign-ups can slip through simultaneously. Please confirm (or add) a unique index/constraint on the username column in your database. For example, in a migration:

ALTER TABLE users
ADD CONSTRAINT unique_username UNIQUE (username);

This guarantees atomic failure on duplicate usernames, regardless of concurrent requests.

Frontend/src/pages/ResetPassword.tsx (3)

1-5: LGTM! Proper Supabase integration for password reset.

The refactor to use supabase.auth.updateUser and rely on Supabase's session management is the correct approach. Removing manual token handling simplifies the flow and improves security.

Also applies to: 20-23


56-64: Good error handling implementation.

The error handling properly catches and displays Supabase errors while providing a fallback message. This gives users helpful feedback during the password reset process.


92-129: Well-implemented success state with progress feedback.

The success state with progress bar and countdown provides excellent user feedback and automatically redirects after completion. The UI clearly communicates what's happening to the user.

Frontend/src/pages/ForgotPassword.tsx (3)

4-4: Excellent email verification flow implementation.

The addition of email existence checking before sending reset emails is a great UX improvement. It prevents confusion and provides helpful guidance when users don't have accounts.

Also applies to: 20-36


108-112: Good signup prompt for better user guidance.

The yellow warning box with signup link provides clear guidance for users who don't have accounts. This reduces confusion and improves the user experience.


32-35: Proper Supabase password reset integration.

Using resetPasswordForEmail with a proper redirect URL ensures users are directed back to the application after clicking the reset link. The window.location.origin ensures the redirect works across different environments.


setIsLoading(false);
navigate(`/BasicDetails/${user}`);
navigate(`/BasicDetails/${accountType}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Validate accountType before navigation.

The navigation uses accountType directly without validation. Ensure it contains expected values to prevent invalid routes.

+     const validAccountTypes = ["creator", "brand"];
+     const safeAccountType = validAccountTypes.includes(accountType) ? accountType : "creator";
-     navigate(`/BasicDetails/${accountType}`);
+     navigate(`/BasicDetails/${safeAccountType}`);
πŸ“ 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.

Suggested change
navigate(`/BasicDetails/${accountType}`);
// Validate accountType before navigation
const validAccountTypes = ["creator", "brand"];
const safeAccountType = validAccountTypes.includes(accountType) ? accountType : "creator";
navigate(`/BasicDetails/${safeAccountType}`);
πŸ€– Prompt for AI Agents
In Frontend/src/pages/Signup.tsx at line 98, the code navigates using
accountType without validating it. Add a check to confirm accountType is one of
the expected valid values before calling navigate. If it is invalid, handle the
case appropriately, such as showing an error or defaulting to a safe route, to
prevent navigation to invalid routes.

Comment on lines 197 to 214
<div className="space-y-2">
<label
htmlFor="username"
className="text-sm font-medium text-gray-700 dark:text-gray-300"
>
Username
</label>
<input
id="username"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 dark:focus:ring-purple-400 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition-all duration-200"
placeholder="Choose a unique username"
/>
</div>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

πŸ› οΈ Refactor suggestion

Add comprehensive username input validation.

The username input lacks validation attributes and real-time feedback. Consider adding pattern validation and length constraints.

                      <input
                        id="username"
                        name="username"
                        type="text"
                        value={formData.username}
                        onChange={handleChange}
                        required
+                       minLength={3}
+                       maxLength={20}
+                       pattern="[a-zA-Z0-9_]+"
                        className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 dark:focus:ring-purple-400 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition-all duration-200"
                        placeholder="Choose a unique username"
                      />
πŸ“ 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.

Suggested change
<div className="space-y-2">
<label
htmlFor="username"
className="text-sm font-medium text-gray-700 dark:text-gray-300"
>
Username
</label>
<input
id="username"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 dark:focus:ring-purple-400 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition-all duration-200"
placeholder="Choose a unique username"
/>
</div>
<div className="space-y-2">
<label
htmlFor="username"
className="text-sm font-medium text-gray-700 dark:text-gray-300"
>
Username
</label>
<input
id="username"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
minLength={3}
maxLength={20}
pattern="[a-zA-Z0-9_]+"
className="w-full px-4 py-3 rounded-lg border border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 dark:focus:ring-purple-400 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white transition-all duration-200"
placeholder="Choose a unique username"
/>
</div>
πŸ€– Prompt for AI Agents
In Frontend/src/pages/Signup.tsx around lines 197 to 214, the username input
field lacks validation attributes and real-time feedback. Add HTML validation
attributes such as pattern to enforce allowed characters, minLength and
maxLength for length constraints. Implement real-time validation in the onChange
handler to provide immediate user feedback on invalid input, and display error
messages below the input field when validation fails.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 comments (1)
Frontend/src/pages/Signup.tsx (1)

128-143: ⚠️ Potential issue

Google OAuth signup lacks username handling.

The Google OAuth signup flow doesn't account for the new username requirement. Users signing up via Google won't have a username set, which could cause issues in the application.

Consider implementing a username selection step for OAuth users:

  const handleGoogleSignUp = async () => {
    const { data, error } = await supabase.auth.signInWithOAuth({
      provider: "google",
+     options: {
+       redirectTo: `${window.location.origin}/complete-profile`
+     }
    });

    if (error) {
      console.log("Google login error", error);
      return;
    }

-   supabase.auth.onAuthStateChange((event, session) => {
-     if (session) {
-       login();
-     }
-   });
+   // Handle OAuth completion in a separate component/page
+   // where users can set their username
  };
♻️ Duplicate comments (4)
Frontend/src/pages/Signup.tsx (4)

68-78: Consider implementing case-insensitive username uniqueness check.

The current implementation checks for exact username matches, but usernames are typically treated as case-insensitive to prevent confusion (e.g., "User1" and "user1" should be considered the same).

This aligns with the previous review comment about case sensitivity handling.


96-110: Remove password_hash field and let database handle timestamps.

The user insertion includes problematic fields that should be addressed:

This matches the previous review comments about password_hash and timestamp handling concerns.


227-239: Add HTML validation attributes to username input.

The username input field lacks native HTML validation attributes that would provide immediate browser-level feedback.

This was addressed in a previous review comment about adding validation attributes like pattern, minLength, and maxLength.


120-120: Validate accountType before navigation.

This was previously identified as needing validation to prevent navigation to invalid routes.

🧹 Nitpick comments (2)
Frontend/src/pages/Signup.tsx (2)

37-44: Username validation regex could be more restrictive for better UX.

The current regex allows usernames like a__ (letter followed by underscores) which might not provide the best user experience. Consider requiring at least one alphanumeric character after the initial letter.

-  const regex = /^[a-zA-Z][a-zA-Z0-9_]{2,19}$/;
+  const regex = /^[a-zA-Z][a-zA-Z0-9]*[a-zA-Z0-9_]*[a-zA-Z0-9]$|^[a-zA-Z][a-zA-Z0-9]{1,18}$/;

Alternatively, use a simpler approach that prevents consecutive underscores and trailing underscores:

-  const regex = /^[a-zA-Z][a-zA-Z0-9_]{2,19}$/;
+  const regex = /^[a-zA-Z](?!.*__)[a-zA-Z0-9_]{2,18}[a-zA-Z0-9]$/;

57-63: Improve error handling for validation feedback.

The validation check prevents submission but doesn't reset the loading state consistently with the username uniqueness check pattern.

Consider extracting the validation and loading state reset into a helper function:

    // Validate username before submitting
    const usernameValidation = validateUsername(formData.username);
    if (usernameValidation) {
      setUsernameError(usernameValidation);
      setIsLoading(false);
      return;
    }
+   // Clear any previous username errors
+   setUsernameError("");
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 3f8b63d and 795ae23.

πŸ“’ Files selected for processing (3)
  • Backend/app/models/models.py (1 hunks)
  • Backend/app/routes/post.py (1 hunks)
  • Frontend/src/pages/Signup.tsx (5 hunks)
βœ… Files skipped from review due to trivial changes (2)
  • Backend/app/routes/post.py
  • Backend/app/models/models.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
Frontend/src/pages/Signup.tsx (1)
Frontend/src/utils/supabase.tsx (1)
  • supabase (6-6)

@chandansgowda chandansgowda changed the title Made password reset flow functional and also added username selection(with nuinqness check) on the signup form Made password reset flow functional and also added username selection(with uniqueness check) on the signup form Jun 14, 2025
@chandansgowda chandansgowda merged commit 3631e56 into AOSSIE-Org:main Jun 14, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants