Skip to content

Refactor verification handler to extract duplicated error responses#135

Draft
Copilot wants to merge 2 commits intocopilot-hackathonfrom
copilot/fix-53057619-946651225-e97d8a27-54b4-4c6c-a803-34d2288945a9
Draft

Refactor verification handler to extract duplicated error responses#135
Copilot wants to merge 2 commits intocopilot-hackathonfrom
copilot/fix-53057619-946651225-e97d8a27-54b4-4c6c-a803-34d2288945a9

Conversation

Copy link

Copilot AI commented Nov 3, 2025

The handleVerify function mixed request decoding, service calls, logging, and response construction in 60 lines with three near-identical error response blocks. This made the flow hard to follow and increased drift risk.

Changes

Extracted helpers:

  • sendWebhookError() - Centralizes WebhookErrorResponse construction and encoding
  • parsePayload() - Decodes request body to WebhookPayload
  • verifyEmployee() - Wraps service call with AuthzFailureNotEmployee logging

Refactored handler:

func (a *API) handleVerify(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()

    // Parse the payload
    payload, err := parsePayload(r)
    if err != nil {
        a.logger.Error("Failed to parse payload: ", err)
        sendWebhookError(w, http.StatusBadRequest, InvalidPayload, "Invalid payload", "")
        return
    }

    // Verify the user is an employee
    isEmployee, err := a.verifyEmployee(r, payload.Email)
    if err != nil {
        sendWebhookError(w, http.StatusForbidden, APICallFailure, "Failed to call the salesforce API", "")
        return
    }

    if !isEmployee {
        sendWebhookError(w, http.StatusForbidden, NotFound, "User is not an employee", "#/traits/email")
        return
    }

    // Success: echo the original payload
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(payload)
}

Handler reduced from 60 to 27 lines. Error literals and response structure now live in one place. Security logging centralized in verifyEmployee(). Success response unchanged.

Tests added:

  • TestSendWebhookError() - Validates error response structure for all variants
  • TestParsePayload() - Covers valid/invalid JSON cases
  • TestVerifyEmployee() - Verifies security logging behavior
Original prompt

This section details on the original issue you should resolve

<issue_title>Refactor Verification handler</issue_title>
<issue_description>## Summary
pkg/user_verification/handlers.go:handleVerify mixes request decoding, service calls, logging, and response construction in one tight block. Three near-identical error responses are hand-built, and every response path writes headers and encodes JSON inline. This makes the flow harder to follow and increases the chance of drift when future error cases or logging changes arrive.

Proposed changes

  • Extract helpers for building/encoding WebhookErrorResponse variants so we don’t repeat literals and header handling.
  • Move payload parsing, service invocation, and success response into named helpers to leave the handler as a clear control flow.
  • Keep the success response identical (webhook should still echo the original payload) while centralising logging—including Security().AuthzFailureNotEmployee.
  • Add focused unit tests around the new helper(s) and updated handler paths.

Motivation

Upcoming logging/auth work will likely introduce more branches. Refactoring now reduces duplication, clarifies the flow, and lowers the risk of inconsistent error payloads.

Acceptance criteria

  • Handler reads primarily as orchestration with descriptive helper names.
  • All error responses are produced through shared helper(s); literals live in one place.
  • Success path still returns the original payload with 200 OK.
  • Tests cover helper behaviour and handler outcomes.</issue_description>

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Co-authored-by: nsklikas <19745916+nsklikas@users.noreply.github.com>
Copilot AI changed the title [WIP] Refactor Verification handler Refactor verification handler to extract duplicated error responses Nov 3, 2025
Copilot AI requested a review from nsklikas November 3, 2025 10:59
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