Skip to content

fix(auth): ensure auth endpoints return JSON when config load fails#273

Open
rushikesh249 wants to merge 2 commits intoAOSSIE-Org:mainfrom
rushikesh249:fix/auth-json-responses
Open

fix(auth): ensure auth endpoints return JSON when config load fails#273
rushikesh249 wants to merge 2 commits intoAOSSIE-Org:mainfrom
rushikesh249:fix/auth-json-responses

Conversation

@rushikesh249
Copy link

@rushikesh249 rushikesh249 commented Jan 27, 2026

Fixes #243

Problem

When configuration loading failed, authentication endpoints could return empty or malformed responses due to improper error handling.
Additionally, duplicate response writes caused runtime warnings like:
"http: superfluous response.WriteHeader call"

Resolution

  • Removed a duplicate SignUp function that caused compilation errors
  • Ensured handlers do not write an extra JSON response when loadConfig() fails, since it already sends an error response
  • Updated SignUp and Login to simply return when configuration loading fails

This prevents double response writes and ensures consistent, valid JSON error handling across authentication endpoints.

@coderabbitai
Copy link

coderabbitai bot commented Jan 27, 2026

📝 Walkthrough

Walkthrough

Adds a GET /health endpoint and replaces the previous VerifyEmail auth flow with a SignUp flow that validates input, prevents duplicate emails, hashes passwords, creates unverified users with verification codes, stores them in MongoDB, and sends verification emails.

Changes

Cohort / File(s) Summary
Health Check Endpoint
backend/cmd/server/main.go
Adds GET /health returning {"status":"ok"} (no auth)
Authentication Controller Refactor
backend/controllers/auth.go
Replaces VerifyEmail flow with SignUp: binds SignUpRequest, checks existing user by email, hashes password, generates verification code, inserts unverified user into MongoDB, sends verification email, removes legacy helpers and VerifyEmail handler; preserves Login/GoogleLogin with adjusted flow
Go Module
go.mod
Module file present/updated (lines changed: +7)

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SignUpHandler as SignUp Handler
    participant Database as MongoDB
    participant EmailService as Email Service

    Client->>SignUpHandler: POST /signup (email, password)
    SignUpHandler->>SignUpHandler: Validate SignUpRequest
    SignUpHandler->>Database: Find user by email
    Database-->>SignUpHandler: User exists? 
    alt User exists
        SignUpHandler-->>Client: Error response (user exists)
    else New user
        SignUpHandler->>SignUpHandler: Hash password & generate code
        SignUpHandler->>Database: Insert unverified user with code
        Database-->>SignUpHandler: Insert OK
        SignUpHandler->>EmailService: Send verification email(code)
        EmailService-->>SignUpHandler: Email sent
        SignUpHandler-->>Client: Success response (no JWT)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I baked a signup code in a burrow so neat,

Passwords are hashed, and emails take fleet,
Health pings a hello, all systems in tune,
Verification moonlights beneath the same moon,
Hoppity hop — auth hops along to a new beat.

🚥 Pre-merge checks | ✅ 1 | ❌ 4
❌ Failed checks (3 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title mentions returning JSON when config load fails, but the actual changes include a complete auth flow replacement from VerifyEmail to SignUp, with hundreds of lines removed and significant restructuring unrelated to the stated fix. Update title to accurately reflect the major auth flow refactoring including SignUp implementation, user creation, and verification code generation instead of focusing narrowly on config error handling.
Out of Scope Changes check ⚠️ Warning The pull request contains substantial out-of-scope changes including replacing VerifyEmail with SignUp, removing 192 lines from auth.go, and removing multiple helper functions (normalizeUserStats, persistUserStats, sanitize/format helpers) unrelated to the config error handling fix described in the title. Consider splitting the PR into two separate changes: one for the config error handling fix (issue #243) and another for the auth flow refactoring, or provide justification for why the extensive refactoring is necessary for the stated objective.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Linked Issues check ❓ Inconclusive The PR addresses issue #243 by ensuring JSON responses in auth endpoints, but the raw_summary shows extensive changes (SignUp flow replacement, VerifyEmail removal, helper function cleanup) that go significantly beyond the stated objective of adding JSON error handling for config load failures. Clarify whether the extensive auth flow refactoring was intentional or if the PR scope expanded beyond the original fix objective. Verify that all changes align with issue #243's core requirement of consistent JSON responses.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks 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

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

🤖 Fix all issues with AI agents
In `@backend/controllers/auth.go`:
- Around line 286-291: The handler is double-writing a JSON error because
loadConfig() already sends a response before returning nil; remove the redundant
ctx.JSON call in the nil-check for cfg (the block that calls ctx.JSON(500,
gin.H{"error":"Server configuration error"}) and then return) and simply return
when cfg == nil, relying on loadConfig() to have sent the error; locate the nil
check around where cfg is set in the auth handler (the cfg variable and call to
loadConfig()) and remove the extra ctx.JSON invocation to avoid double response
writes.
- Around line 203-210: Delete the duplicate SignUp function (the earlier
definition) so there is only one SignUp in the package, and in the remaining
SignUp remove the redundant ctx.JSON(...) error response after calling
loadConfig() (since loadConfig() already writes the error and returns nil); use
loadConfig()'s nil check to return early without writing another response.
Ensure you only keep a single SignUp function and that it calls loadConfig(ctx)
and returns if cfg == nil.
🧹 Nitpick comments (1)
backend/controllers/auth.go (1)

539-550: Clarify error handling strategy for consistency.

The loadConfig helper already sends a JSON error response on line 546 before returning nil. This means handlers like GoogleLogin, ForgotPassword, VerifyForgotPassword, and VerifyToken that simply return when cfg == nil are already returning valid JSON to clients.

If you want custom error messages per handler, consider refactoring loadConfig to return the error without writing to the response, then let each handler decide the message. Otherwise, remove the redundant ctx.JSON() calls from SignUp and Login to maintain consistency.

Option: Refactor loadConfig to not write response
-func loadConfig(ctx *gin.Context) *config.Config {
+func loadConfig(ctx *gin.Context) (*config.Config, error) {
 	cfgPath := os.Getenv("CONFIG_PATH")
 	if cfgPath == "" {
 		cfgPath = "./config/config.prod.yml"
 	}
 	cfg, err := config.LoadConfig(cfgPath)
 	if err != nil {
-		ctx.JSON(500, gin.H{"error": "Internal server error"})
-		return nil
+		return nil, err
 	}
-	return cfg
+	return cfg, nil
 }

Then each handler can decide the error message:

cfg, err := loadConfig(ctx)
if err != nil {
    ctx.JSON(500, gin.H{"error": "Server configuration error"})
    return
}

Comment on lines 203 to 210
func SignUp(ctx *gin.Context) {
cfg := loadConfig(ctx)
if cfg == nil {
ctx.JSON(500, gin.H{
"error": "Server configuration error",
})
return
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Duplicate function definition will cause compilation error.

There are two SignUp functions defined in this file (lines 124-201 and lines 203-282). Go does not allow multiple functions with the same name and signature in the same package. The first SignUp function (lines 124-201) should be removed.

Additionally, the JSON error response at lines 206-208 is redundant because loadConfig() already writes a JSON error response (line 546) before returning nil. Writing two responses will cause runtime issues like "http: superfluous response.WriteHeader call".

Proposed fix: Remove the duplicate JSON response

If you keep the first SignUp function removed (as intended), the second SignUp should not add another JSON response:

 func SignUp(ctx *gin.Context) {
 	cfg := loadConfig(ctx)
 	if cfg == nil {
-		ctx.JSON(500, gin.H{
-			"error": "Server configuration error",
-		})
 		return
 	}

Alternatively, if you want custom error messages per handler, modify loadConfig to not send a response and let callers handle it.

📝 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
func SignUp(ctx *gin.Context) {
cfg := loadConfig(ctx)
if cfg == nil {
ctx.JSON(500, gin.H{
"error": "Server configuration error",
})
return
}
func SignUp(ctx *gin.Context) {
cfg := loadConfig(ctx)
if cfg == nil {
return
}
🤖 Prompt for AI Agents
In `@backend/controllers/auth.go` around lines 203 - 210, Delete the duplicate
SignUp function (the earlier definition) so there is only one SignUp in the
package, and in the remaining SignUp remove the redundant ctx.JSON(...) error
response after calling loadConfig() (since loadConfig() already writes the error
and returns nil); use loadConfig()'s nil check to return early without writing
another response. Ensure you only keep a single SignUp function and that it
calls loadConfig(ctx) and returns if cfg == nil.

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.

Auth endpoints (/signup, /login) return empty responses instead of JSON on error

1 participant