Skip to content
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

feat(frontend): Add confirm password and fix sign up problem when user does not verify. #188

Merged
merged 16 commits into from
Mar 17, 2025

Conversation

ZHallen122
Copy link
Collaborator

@ZHallen122 ZHallen122 commented Mar 16, 2025

image

image

Summary by CodeRabbit

  • New Features
    • Enhanced registration with a password confirmation step, ensuring passwords match and meet minimum length requirements.
    • Real-time password strength feedback and improved error messaging during sign-up.
    • An additional sign-up option via GitHub.
    • Smoothed registration flow with updates to handle unconfirmed emails more effectively.
    • Improved sign-up modal layout for clearer user instructions and better responsiveness.

@ZHallen122 ZHallen122 requested a review from Sma1lboy March 16, 2025 16:00
Copy link
Contributor

coderabbitai bot commented Mar 16, 2025

Walkthrough

This update enhances the user registration process by adding password confirmation and additional validations. In the backend, the registration logic now accepts a confirmPassword parameter to verify that passwords match, adjusts user handling based on email confirmation state, and enforces a minimum password length. The frontend sign-up modal is updated with real-time password strength evaluation, displays error messages for mismatches or weak passwords, and includes a GitHub sign-up option.

Changes

File(s) Change Summary
backend/.../auth.service.ts, backend/.../register-user.input.ts, backend/.../user.resolver.ts Updated registration logic to include a new confirmPassword parameter, added validations to ensure passwords match, enforced minimum password length, and modified the handling of existing users based on email confirmation status.
frontend/.../sign-up-modal.tsx Enhanced the sign-up modal with a password confirmation input, introduced real-time password strength validation, improved error handling for mismatched/invalid passwords, revised layout management, and added a GitHub sign-up button.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant UI as SignUpModal
    participant Resolver as UserResolver
    participant Auth as AuthService
    participant DB as Database
    participant Email as EmailService

    UI->>UI: Validate password strength & match locally
    UI->>Resolver: Submit registration data
    Resolver->>Auth: Call register() with user input
    Auth->>Auth: Check if password matches confirmPassword
    alt Passwords do not match
        Auth-->>Resolver: Return error "Passwords do not match"
    else
        Auth->>DB: Check for existing user by email
        alt User exists and unconfirmed
            Auth->>DB: Update user with new credentials
            Auth->>Email: Resend verification email
        else User exists and confirmed
            Auth-->>Resolver: Return error "Email already exists"
        else New user
            Auth->>DB: Create new user
            Auth->>Email: Send verification email
        end
    end
    Resolver-->>UI: Return registration outcome

Poem

I’m a rabbit with a spring in my hop,
New checks and validations make my heart go pop!
Passwords now twirl in a matching dance,
With strength and care, they find their chance.
My code garden blooms, clean and sleek—
Hopping along with joy every week! 🥕
Let’s celebrate with a nibble of innovation!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

frontend/src/components/sign-up-modal.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the config "next/core-web-vitals" to extend from. Please check that the name of the config is correct.

The config "next/core-web-vitals" was referenced from the config file in "/frontend/.eslintrc.json".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/auth/auth.service.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/user/dto/register-user.input.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

  • 1 others

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

Sorry, something went wrong.

autofix-ci bot and others added 14 commits March 16, 2025 16:01
…y/codefox into feat-frontend-fix-signup
…y/codefox into feat-frontend-fix-signup
…y/codefox into feat-frontend-fix-signup
…y/codefox into feat-frontend-fix-signup
@ZHallen122 ZHallen122 marked this pull request as ready for review March 16, 2025 23:59
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

🧹 Nitpick comments (5)
backend/src/user/user.resolver.ts (1)

66-68: Consider using built-in NestJS exceptions instead of generic Error

Your password validation logic is correct, but using a generic Error doesn't align with NestJS's standard error handling practices.

-    if (registerUserInput.password.length < 6) {
-      throw new Error('Password must be at least 6 characters');
-    }
+    if (registerUserInput.password.length < 6) {
+      throw new BadRequestException('Password must be at least 6 characters');
+    }

Don't forget to import BadRequestException from @nestjs/common at the top of the file.

backend/src/user/dto/register-user.input.ts (1)

16-19: Consider adding a custom validator for password matching

While the password matching logic is currently in the service layer, you might consider adding a custom validator to ensure passwords match at the DTO level.

This would ensure validation happens before reaching your service logic:

import { InputType, Field } from '@nestjs/graphql';
import { IsEmail, IsString, MinLength, Validate } from 'class-validator';

// Example custom validator (would need to be implemented)
class PasswordsMatchConstraint {
  validate(registerUserInput: any) {
    return registerUserInput.password === registerUserInput.confirmPassword;
  }
  
  defaultMessage() {
    return 'Passwords do not match';
  }
}

@InputType()
export class RegisterUserInput {
  // existing fields...
  
  @Validate(PasswordsMatchConstraint)
  confirmPassword: string;
}
backend/src/auth/auth.service.ts (2)

158-168: Improved user registration flow for unconfirmed emails

The logic for handling existing users has been improved to update the user's information if their email is not confirmed, rather than rejecting the registration outright.

Consider adding a rate limit or cooldown for unconfirmed email updates to prevent abuse. Someone could repeatedly attempt to register with another person's email, potentially changing their username/password if they eventually confirm.

 // If the user exists but email is not confirmed and mail is enabled
 if (existingUser && !existingUser.isEmailConfirmed && this.isMailEnabled) {
+  // Check if a cooldown period has passed (similar to your email resend cooldown)
+  const cooldownPeriod = 5 * 60 * 1000; // 5 minutes in milliseconds
+  if (
+    existingUser.lastRegistrationAttempt &&
+    new Date().getTime() - existingUser.lastRegistrationAttempt.getTime() < cooldownPeriod
+  ) {
+    throw new ConflictException('Please wait before trying to register with this email again');
+  }
+
   // Just update the existing user and resend verification email
   existingUser.username = username;
   existingUser.password = hashedPassword;
+  existingUser.lastRegistrationAttempt = new Date();
   await this.userRepository.save(existingUser);
   await this.sendVerificationEmail(existingUser);
   return existingUser;

This would require adding a lastRegistrationAttempt field to the User entity.


158-168: Consider refactoring complex conditional logic

The nested conditional logic for handling existing users can be difficult to maintain. Consider refactoring into a more structured approach.

You could extract this logic into separate, well-named methods:

private async handleExistingUser(existingUser: User, username: string, hashedPassword: string): Promise<User> {
  if (!existingUser.isEmailConfirmed && this.isMailEnabled) {
    return this.updateUnconfirmedUser(existingUser, username, hashedPassword);
  }
  
  throw new ConflictException('Email already exists');
}

private async updateUnconfirmedUser(user: User, username: string, hashedPassword: string): Promise<User> {
  user.username = username;
  user.password = hashedPassword;
  await this.userRepository.save(user);
  await this.sendVerificationEmail(user);
  return user;
}

Then your register method would be cleaner:

async register(registerUserInput: RegisterUserInput): Promise<User> {
  // Validation code...
  
  const existingUser = await this.userRepository.findOne({
    where: { email },
  });
  
  if (existingUser) {
    return this.handleExistingUser(existingUser, username, hashedPassword);
  }
  
  // Create new user code...
}
frontend/src/components/sign-up-modal.tsx (1)

52-87: Well-implemented password validation function

The password validation function provides comprehensive checks and appropriate feedback to users.

Consider extracting the regex patterns to constants to avoid duplication and improve maintainability. These patterns are used in both the validation function and the UI display:

// At the top of your file or in a separate utils file
const PASSWORD_PATTERNS = {
  UPPERCASE: /[A-Z]/,
  LOWERCASE: /[a-z]/,
  NUMBERS: /\d/,
  SPECIAL_CHARS: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/
};

// Then in your validation function
const hasUppercase = PASSWORD_PATTERNS.UPPERCASE.test(value);
// etc.

// And in your UI
<li className={PASSWORD_PATTERNS.UPPERCASE.test(password) ? 'text-green-500' : ''}>
  Include at least one uppercase letter
</li>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4cc75d6 and e4047df.

📒 Files selected for processing (4)
  • backend/src/auth/auth.service.ts (1 hunks)
  • backend/src/user/dto/register-user.input.ts (1 hunks)
  • backend/src/user/user.resolver.ts (1 hunks)
  • frontend/src/components/sign-up-modal.tsx (7 hunks)
🔇 Additional comments (10)
backend/src/user/user.resolver.ts (1)

66-68: Validation duplication with DTO

This validation duplicates the @MinLength(6) decorator already present in the DTO. While redundant validation doesn't hurt, it creates a maintenance burden if requirements change.

Consider whether this validation could be removed since class-validator should handle it, or ensure it's consistent with the DTO validation. If you prefer belt-and-suspenders validation, you might want to extract the minimum length to a constant shared between files.

backend/src/user/dto/register-user.input.ts (1)

16-19: LGTM! Good addition of confirmPassword field

The confirmPassword field has been properly set up with appropriate decorators matching the password field constraints.

backend/src/auth/auth.service.ts (2)

145-146: LGTM! Added confirmPassword parameter extraction

Correctly extracting the new confirmPassword field from the input.


152-154: LGTM! Password matching validation

Good addition of password matching validation before continuing with registration.

frontend/src/components/sign-up-modal.tsx (6)

46-50: LGTM! Added state variables for password confirmation and validation

Good addition of state variables to manage password confirmation, error messages, and strength indicators.


111-118: LGTM! Improved form validation

Good implementation of password validation and confirmation checks before submission.


127-127: LGTM! Added confirmPassword to form submission

Correctly including the confirmPassword field in the GraphQL mutation.


275-310: Verify social login functionality

The UI for social login buttons has been added, but it's unclear if the backend integration exists to support this functionality.

Make sure the backend has corresponding OAuth integration for Google and GitHub login, or add a TODO comment if this feature is planned for future implementation.


358-426: Great implementation of password strength meter and requirements list

The password strength visualization and detailed requirements list with real-time feedback provides an excellent user experience.

This implementation gives users clear feedback about password requirements and helps them create stronger passwords.


429-442: LGTM! Added password confirmation field

Good implementation of the confirmation password field matching the UX of the original password field.

@Sma1lboy Sma1lboy changed the title Feat(frontend): Add confirm password and fix sign up problem when user does not verify. feat(frontend): Add confirm password and fix sign up problem when user does not verify. Mar 17, 2025
@Sma1lboy Sma1lboy merged commit 17ea0df into main Mar 17, 2025
4 of 5 checks 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.

None yet

2 participants