Skip to content

Conversation

@Naitik1886
Copy link

@Naitik1886 Naitik1886 commented Nov 22, 2025

Fix: Issue #66 - Incorrect Input Validation for Email/Password in Authentication

Solved - Updated the old email regex with the standard one.
Also fixed the unclear error messaging .

Summary by CodeRabbit

  • Bug Fixes

    • Clarified error wording for invalid email context values to more accurately reflect internal validation.
  • Behavior Changes

    • Display-name derivation now only extracts a username when the input matches a valid email pattern; otherwise the full input (email or original string) is shown.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 22, 2025

Walkthrough

Changed two room handlers' error text for non-string email context values. Modified email-name extraction to only return the local part when the input fully matches an email pattern; otherwise the original input is returned.

Changes

Cohort / File(s) Summary
Room route error messages
backend/routes/rooms.go
Updated error response message in JoinRoomHandler and GetRoomParticipantsHandler for non-string email context value to "Internal error: email context value is not a string" (HTTP status unchanged).
Email name extraction logic
backend/utils/auth.go
Tightened ExtractNameFromEmail regex to require a full-email match; function now returns the captured local part only when the input matches the email pattern, otherwise returns the original input. No exported signatures changed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review callers of ExtractNameFromEmail to ensure they handle either a username (local part) or the original input when non-email values are passed.
  • Confirm the new error wording in rooms.go aligns with logging/monitoring and does not hide actionable diagnostic details for clients.

Poem

🐰 I hopped through code with gentle care,

I changed a message, tuned a snare,
Now names appear when emails fit,
Else the input stays as-is a bit,
A small white hop — a tidy repair. 🥕

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: updating the email regex pattern in auth.go and improving error messages in the handlers in rooms.go.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/utils/auth.go (1)

38-46: Critical: Regex missing capturing group breaks username extraction.

The regex pattern lacks capturing groups, so FindStringSubmatch returns only the full matched email in match[0]. The condition len(match) < 2 will always be true, causing the function to return the full email instead of extracting the username. This breaks the function's documented purpose and affects multiple callers.

Usages impacted:

  • backend/controllers/auth.go:59 — fallback when nickname is empty
  • backend/controllers/auth.go:160–161 — setting DisplayName and Nickname on user creation
  • backend/controllers/leaderboard.go:70 — fallback when DisplayName is empty

Apply this diff to fix:

-	re := regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
+	re := regexp.MustCompile(`^([a-zA-Z0-9._%+-]+)@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 26aff7c and 697e7b4.

📒 Files selected for processing (2)
  • backend/routes/rooms.go (2 hunks)
  • backend/utils/auth.go (1 hunks)

@Naitik1886 Naitik1886 changed the title changed old email regex to standard one Update email regex pattern and improve error messages in auth handlers' . Nov 22, 2025
Copy link

@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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bda7565 and d7cd967.

📒 Files selected for processing (1)
  • backend/utils/auth.go (1 hunks)
🔇 Additional comments (1)
backend/utils/auth.go (1)

39-46: Email validation via struct binding tags mitigates behavior change concerns.

The SignUpRequest struct enforces email validation with binding:"required,email" on the Email field, which Gin validates before the handler executes. This ensures request.Email at lines 160–161 is always a valid email format. Other call sites use existing user emails (from the database) or trusted sources (Google tokens). The new behavior—returning the original input when the pattern doesn't match—is actually safer than unconditionally extracting before '@'. No code changes required.

// ExtractNameFromEmail extracts the username before '@'
func ExtractNameFromEmail(email string) string {
re := regexp.MustCompile(`^([^@]+)`)
re := regexp.MustCompile(`^([a-zA-Z0-9._%+-]+)@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Move regex compilation to package level and address pattern edge cases.

The regex is compiled on every function call, which is inefficient. Additionally, the current pattern has edge cases that allow technically invalid emails:

Apply this diff to move the regex to package level and tighten the pattern:

+var emailRegex = regexp.MustCompile(`^([a-zA-Z0-9]+(?:[._%-][a-zA-Z0-9]+)*)@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$`)
+
 // ExtractNameFromEmail extracts the username before '@'
 func ExtractNameFromEmail(email string) string {
-	re := regexp.MustCompile(`^([a-zA-Z0-9._%+-]+)@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
-	match := re.FindStringSubmatch(email)
+	match := emailRegex.FindStringSubmatch(email)
 	if len(match) < 2 {
 		return email
 	}

The improved pattern:

  • Prevents consecutive special characters
  • Prevents leading/trailing special characters
  • Ensures domain labels don't start/end with hyphens

Alternatively, if the current pattern is intentionally lenient for your use case, at minimum move the compilation to package level for performance.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In backend/utils/auth.go around line 40, the email regexp is compiled on each
call and allows edge cases (consecutive or leading/trailing dots in local part
and domain labels starting/ending with hyphens); move the regexp compilation to
a package-level variable and replace the per-call Compile/Match with that
precompiled var, and tighten the pattern to disallow consecutive special
characters and leading/trailing dots in the local part and disallow domain
labels that start or end with hyphens (i.e. use a single compiled pattern that
enforces no consecutive special chars, no leading/trailing special chars, and
domain label rules).

@bhavik-mangla
Copy link
Contributor

^([a-zA-Z0-9._%+-]+)@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This is a full email validation regex, not a "capture the name" regex.
It matches the whole email, not just the username

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