general cleanup - removed old comments, enforced naming conventions etc
Some checks are pending
check / check (push) Waiting to run
Some checks are pending
check / check (push) Waiting to run
This commit is contained in:
159
backend/internal/handlers/address.go
Normal file
159
backend/internal/handlers/address.go
Normal file
@@ -0,0 +1,159 @@
|
||||
// Package handlers implements HTTP request handlers for the API.
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
)
|
||||
|
||||
var ethAddressRe = regexp.MustCompile(`^0x[a-fA-F0-9]{40}$`)
|
||||
|
||||
type AddressHandler struct {
|
||||
addresses *models.AddressModel
|
||||
}
|
||||
|
||||
func NewAddressHandler(addresses *models.AddressModel) *AddressHandler {
|
||||
return &AddressHandler{addresses: addresses}
|
||||
}
|
||||
|
||||
func (h *AddressHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
var body struct {
|
||||
Address string `json:"address"`
|
||||
Label *string `json:"label"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
log.Printf("Failed to decode address request body: %v", err)
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if body.Address == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Address is required")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !ethAddressRe.MatchString(body.Address) {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid Ethereum address format")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s creating address: %s", userID, body.Address)
|
||||
|
||||
addr, err := h.addresses.Create(r.Context(), userID, body.Address, body.Label)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "23505") || strings.Contains(err.Error(), "unique") {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "You are already tracking this address")
|
||||
|
||||
return
|
||||
}
|
||||
log.Printf("Error creating address: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to create address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Address created with ID: %d", addr.ID)
|
||||
writeJSON(w, http.StatusCreated, addr)
|
||||
}
|
||||
|
||||
// List handles GET requests to list all tracked addresses for the current user.
|
||||
func (h *AddressHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
log.Printf("User %s listing addresses", userID)
|
||||
|
||||
addresses, err := h.addresses.ListByUser(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error listing addresses: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to list addresses")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if addresses == nil {
|
||||
addresses = []domain.Address{}
|
||||
}
|
||||
|
||||
log.Printf("Found %d addresses for user", len(addresses))
|
||||
writeJSON(w, http.StatusOK, addresses)
|
||||
}
|
||||
|
||||
// handles PATCH requests to update an address label.
|
||||
func (h *AddressHandler) UpdateLabel(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
addressID, ok := parseIntParam(r.PathValue("addressId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid address ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Label *string `json:"label"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s updating label for address ID: %d", userID, addressID)
|
||||
|
||||
addr, err := h.addresses.UpdateLabel(r.Context(), addressID, userID, body.Label)
|
||||
if err != nil {
|
||||
log.Printf("Error updating address label: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to update address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if addr == nil {
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Address not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, addr)
|
||||
}
|
||||
|
||||
// Remove handles DELETE requests to remove a tracked address.
|
||||
func (h *AddressHandler) Remove(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
addressID, ok := parseIntParam(r.PathValue("addressId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid address ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s deleting address ID: %d", userID, addressID)
|
||||
|
||||
deleted, err := h.addresses.Remove(r.Context(), addressID, userID)
|
||||
if err != nil {
|
||||
log.Printf("Error deleting address: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to delete address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !deleted {
|
||||
log.Printf("Address %d not found or not owned by user", addressID)
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Address not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Address %d deleted", addressID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
58
backend/internal/handlers/alert_event.go
Normal file
58
backend/internal/handlers/alert_event.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
)
|
||||
|
||||
// AlertEventHandler handles HTTP requests for alert event history.
|
||||
type AlertEventHandler struct {
|
||||
alertEvents *models.AlertEventModel
|
||||
}
|
||||
|
||||
// NewAlertEventHandler creates a new AlertEventHandler.
|
||||
func NewAlertEventHandler(alertEvents *models.AlertEventModel) *AlertEventHandler {
|
||||
return &AlertEventHandler{alertEvents: alertEvents}
|
||||
}
|
||||
|
||||
// List handles GET requests to list recent alert events for the current user.
|
||||
func (h *AlertEventHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
limit := 20
|
||||
if limitStr != "" {
|
||||
if n, err := strconv.Atoi(limitStr); err == nil {
|
||||
limit = n
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("User %s listing alert events (limit: %d)", userID, limit)
|
||||
|
||||
if limit < 1 || limit > 100 {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Limit must be between 1 and 100")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
events, err := h.alertEvents.ListRecentByUser(r.Context(), userID, limit)
|
||||
if err != nil {
|
||||
log.Printf("Error listing alert events: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to list alert events")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Found %d alert events for user", len(events))
|
||||
|
||||
if events == nil {
|
||||
events = []domain.AlertEvent{}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, events)
|
||||
}
|
||||
274
backend/internal/handlers/alert_rule.go
Normal file
274
backend/internal/handlers/alert_rule.go
Normal file
@@ -0,0 +1,274 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
)
|
||||
|
||||
var errThresholdFormat = errors.New("unsupported threshold format")
|
||||
|
||||
type AlertRuleHandler struct {
|
||||
alertRules *models.AlertRuleModel
|
||||
addresses *models.AddressModel
|
||||
}
|
||||
|
||||
func NewAlertRuleHandler(alertRules *models.AlertRuleModel, addresses *models.AddressModel) *AlertRuleHandler {
|
||||
return &AlertRuleHandler{alertRules: alertRules, addresses: addresses}
|
||||
}
|
||||
|
||||
func (h *AlertRuleHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
addressID, ok := parseIntParam(r.PathValue("addressId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid address ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Type string `json:"type"`
|
||||
Threshold json.RawMessage `json:"threshold"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
log.Printf("Failed to decode alert request body: %v", err)
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
threshold, err := parseThreshold(body.Threshold)
|
||||
if err != nil {
|
||||
log.Printf("Failed to parse threshold: %v", err)
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "threshold must be a valid number")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s creating alert: type=%s, addressID=%d", userID, body.Type, addressID)
|
||||
|
||||
if body.Type == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Alert type is required")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if !domain.IsValidAlertType(body.Type) {
|
||||
types := make([]string, len(domain.ValidAlertTypes))
|
||||
for i, t := range domain.ValidAlertTypes {
|
||||
types[i] = t.String()
|
||||
}
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid alert type. Must be one of: "+strings.Join(types, ", "))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
alertType := domain.AlertType(body.Type)
|
||||
if domain.IsThresholdRequired(alertType) {
|
||||
if threshold == nil || *threshold <= 0 {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
fmt.Sprintf("Alert type '%s' requires a positive threshold value", body.Type))
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
addr, err := h.addresses.FindByID(r.Context(), addressID, &userID)
|
||||
if err != nil {
|
||||
log.Printf("Error finding address: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to create alert rule")
|
||||
|
||||
return
|
||||
}
|
||||
if addr == nil {
|
||||
log.Printf("Address %d not found or not owned by user", addressID)
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Address not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
newAlert, err := h.alertRules.Create(r.Context(), addressID, alertType, threshold)
|
||||
if err != nil {
|
||||
log.Printf("Error creating alert rule: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to create alert rule")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Alert rule created with ID: %d", newAlert.ID)
|
||||
writeJSON(w, http.StatusCreated, newAlert)
|
||||
}
|
||||
|
||||
func parseThreshold(raw json.RawMessage) (*float64, error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
// Check null before number -- json.Unmarshal treats null as valid for float64 (sets to 0).
|
||||
if string(raw) == "null" {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
|
||||
var asNumber float64
|
||||
if err := json.Unmarshal(raw, &asNumber); err == nil {
|
||||
return &asNumber, nil
|
||||
}
|
||||
|
||||
var asString string
|
||||
if err := json.Unmarshal(raw, &asString); err == nil {
|
||||
asString = strings.TrimSpace(asString)
|
||||
if asString == "" {
|
||||
return nil, nil //nolint:nilnil
|
||||
}
|
||||
parsed, parseErr := strconv.ParseFloat(asString, 64)
|
||||
if parseErr != nil {
|
||||
return nil, parseErr
|
||||
}
|
||||
|
||||
return &parsed, nil
|
||||
}
|
||||
|
||||
return nil, errThresholdFormat
|
||||
}
|
||||
|
||||
// ListByAddress handles GET requests to list alert rules for an address.
|
||||
func (h *AlertRuleHandler) ListByAddress(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
addressID, ok := parseIntParam(r.PathValue("addressId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid address ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s listing alerts for address ID: %d", userID, addressID)
|
||||
|
||||
addr, err := h.addresses.FindByID(r.Context(), addressID, &userID)
|
||||
if err != nil {
|
||||
log.Printf("Error finding address: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to list alerts")
|
||||
|
||||
return
|
||||
}
|
||||
if addr == nil {
|
||||
log.Printf("Address %d not found or not owned by user", addressID)
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Address not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
alerts, err := h.alertRules.ListByAddress(r.Context(), addressID)
|
||||
if err != nil {
|
||||
log.Printf("Error listing alerts: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to list alerts")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if alerts == nil {
|
||||
alerts = []domain.AlertRule{}
|
||||
}
|
||||
|
||||
log.Printf("Found %d alert rules", len(alerts))
|
||||
writeJSON(w, http.StatusOK, alerts)
|
||||
}
|
||||
|
||||
// UpdateStatus handles PATCH requests to enable or disable an alert rule.
|
||||
func (h *AlertRuleHandler) UpdateStatus(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
alertID, ok := parseIntParam(r.PathValue("alertId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid alert ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
log.Printf("Failed to decode update request body: %v", err)
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s updating alert ID: %d", userID, alertID)
|
||||
|
||||
if body.Enabled == nil {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "enabled must be a boolean value")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
alert, err := h.alertRules.FindByID(r.Context(), alertID, &userID)
|
||||
if err != nil {
|
||||
log.Printf("Error finding alert: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to update alert")
|
||||
|
||||
return
|
||||
}
|
||||
if alert == nil {
|
||||
log.Printf("Alert %d not found or not owned by user", alertID)
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Alert rule not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
updated, err := h.alertRules.UpdateEnabled(r.Context(), alertID, *body.Enabled)
|
||||
if err != nil {
|
||||
log.Printf("Error updating alert: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to update alert")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Alert %d updated: enabled=%v", alertID, *body.Enabled)
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
// Remove handles DELETE requests to remove an alert rule.
|
||||
func (h *AlertRuleHandler) Remove(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
alertID, ok := parseIntParam(r.PathValue("alertId"))
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid alert ID")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s deleting alert ID: %d", userID, alertID)
|
||||
|
||||
alert, err := h.alertRules.FindByID(r.Context(), alertID, &userID)
|
||||
if err != nil {
|
||||
log.Printf("Error finding alert: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to delete alert")
|
||||
|
||||
return
|
||||
}
|
||||
if alert == nil {
|
||||
log.Printf("Alert %d not found or not owned by user", alertID)
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "Alert rule not found")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.alertRules.Remove(r.Context(), alertID); err != nil {
|
||||
log.Printf("Error deleting alert: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to delete alert")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Alert %d deleted", alertID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
252
backend/internal/handlers/alert_rule_test.go
Normal file
252
backend/internal/handlers/alert_rule_test.go
Normal file
@@ -0,0 +1,252 @@
|
||||
//nolint:testpackage // parseThreshold is unexported; internal test package required
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
//nolint:gocognit
|
||||
func TestParseThreshold(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("nil/empty raw message returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val != nil {
|
||||
t.Fatalf("expected nil, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty slice returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage{})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val != nil {
|
||||
t.Fatalf("expected nil, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("JSON null returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage("null"))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val != nil {
|
||||
t.Fatalf("expected nil, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("number 10 returns 10.0", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage("10"))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val == nil {
|
||||
t.Fatal("expected non-nil value")
|
||||
}
|
||||
if *val != 10.0 {
|
||||
t.Fatalf("expected 10.0, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("number 0.5 returns 0.5", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage("0.5"))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val == nil || *val != 0.5 {
|
||||
t.Fatalf("expected 0.5, got %v", val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("string '10' returns 10.0", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage(`"10"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val == nil || *val != 10.0 {
|
||||
t.Fatalf("expected 10.0, got %v", val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("string '0.001' returns 0.001", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage(`"0.001"`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val == nil || math.Abs(*val-0.001) > 1e-9 {
|
||||
t.Fatalf("expected 0.001, got %v", val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("string with spaces ' 10 ' returns 10.0", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage(`" 10 "`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val == nil || *val != 10.0 {
|
||||
t.Fatalf("expected 10.0, got %v", val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty string returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage(`""`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val != nil {
|
||||
t.Fatalf("expected nil, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("whitespace-only string returns nil", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
val, err := parseThreshold(json.RawMessage(`" "`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if val != nil {
|
||||
t.Fatalf("expected nil, got %v", *val)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid string returns error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parseThreshold(json.RawMessage(`"abc"`))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-numeric string")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("boolean returns error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parseThreshold(json.RawMessage("true"))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for boolean")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("array returns error", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
_, err := parseThreshold(json.RawMessage("[1,2]"))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for array")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
//nolint:funlen
|
||||
func TestDecodeAlertBody(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Verifies that the struct used in Create handler can decode all
|
||||
// payload shapes the frontend might send.
|
||||
|
||||
type alertBody struct {
|
||||
Type string `json:"type"`
|
||||
Threshold json.RawMessage `json:"threshold"`
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
payload string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "incoming_tx without threshold",
|
||||
payload: `{"type":"incoming_tx"}`,
|
||||
},
|
||||
{
|
||||
name: "outgoing_tx without threshold",
|
||||
payload: `{"type":"outgoing_tx"}`,
|
||||
},
|
||||
{
|
||||
name: "large_transfer with number threshold",
|
||||
payload: `{"type":"large_transfer","threshold":10}`,
|
||||
},
|
||||
{
|
||||
name: "large_transfer with string threshold",
|
||||
payload: `{"type":"large_transfer","threshold":"10"}`,
|
||||
},
|
||||
{
|
||||
name: "balance_below with number threshold",
|
||||
payload: `{"type":"balance_below","threshold":0.5}`,
|
||||
},
|
||||
{
|
||||
name: "threshold null",
|
||||
payload: `{"type":"incoming_tx","threshold":null}`,
|
||||
},
|
||||
{
|
||||
name: "empty object",
|
||||
payload: `{}`,
|
||||
},
|
||||
{
|
||||
name: "empty body",
|
||||
payload: ``,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var body alertBody
|
||||
err := json.Unmarshal([]byte(tt.payload), &body)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("expected decode error")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected decode error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldStructFailsWithStringThreshold(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
// Documents the original bug: *float64 cannot decode a string threshold.
|
||||
type oldAlertBody struct {
|
||||
Type string `json:"type"`
|
||||
Threshold *float64 `json:"threshold"`
|
||||
}
|
||||
|
||||
payload := `{"type":"large_transfer","threshold":"10"}`
|
||||
var body oldAlertBody
|
||||
err := json.Unmarshal([]byte(payload), &body)
|
||||
if err == nil {
|
||||
t.Fatal("expected error: old struct with *float64 should reject string threshold")
|
||||
}
|
||||
}
|
||||
101
backend/internal/handlers/email_digest.go
Normal file
101
backend/internal/handlers/email_digest.go
Normal file
@@ -0,0 +1,101 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
"github.com/kjannette/koin-ping/backend/internal/services"
|
||||
)
|
||||
|
||||
type EmailDigestHandler struct {
|
||||
digestSvc *services.EmailDigestService
|
||||
configs *models.NotificationConfigModel
|
||||
}
|
||||
|
||||
func NewEmailDigestHandler(
|
||||
digestSvc *services.EmailDigestService,
|
||||
configs *models.NotificationConfigModel,
|
||||
) *EmailDigestHandler {
|
||||
return &EmailDigestHandler{digestSvc: digestSvc, configs: configs}
|
||||
}
|
||||
|
||||
// SetupEmail reads the user's email from their notification config and sends
|
||||
// a confirmation message via Resend to verify the integration works.
|
||||
func (h *EmailDigestHandler) SetupEmail(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
if !h.digestSvc.Configured() {
|
||||
writeError(w, http.StatusServiceUnavailable, "EMAIL_NOT_CONFIGURED",
|
||||
"Email service is not configured on the server")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for email setup: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to load notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil || cfg.Email == nil || *cfg.Email == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Save an email address in notification settings first")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.digestSvc.SetupEmail(*cfg.Email); err != nil {
|
||||
log.Printf("Email setup failed for user %s: %v", userID, err)
|
||||
writeError(w, http.StatusBadGateway, "EMAIL_SEND_FAILED",
|
||||
"Failed to send confirmation email — check server email config")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Email setup confirmation sent to user %s (%s)", userID, *cfg.Email)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"email": *cfg.Email,
|
||||
"message": "Confirmation email sent",
|
||||
})
|
||||
}
|
||||
|
||||
// SendDigest compiles and sends a digest of recent alerts to the user's email.
|
||||
func (h *EmailDigestHandler) SendDigest(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
if !h.digestSvc.Configured() {
|
||||
writeError(w, http.StatusServiceUnavailable, "EMAIL_NOT_CONFIGURED",
|
||||
"Email service is not configured on the server")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for digest: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to load notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil || cfg.Email == nil || *cfg.Email == "" {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"No email address configured")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.digestSvc.SendDigest(r.Context(), userID, *cfg.Email); err != nil {
|
||||
log.Printf("Digest send failed for user %s: %v", userID, err)
|
||||
writeError(w, http.StatusBadGateway, "DIGEST_SEND_FAILED",
|
||||
"Failed to send digest email")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("Digest sent to user %s (%s)", userID, *cfg.Email)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"email": *cfg.Email,
|
||||
"message": "Digest email sent",
|
||||
})
|
||||
}
|
||||
30
backend/internal/handlers/helpers.go
Normal file
30
backend/internal/handlers/helpers.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, errorBody{Error: code, Message: message})
|
||||
}
|
||||
|
||||
func parseIntParam(s string) (int, bool) {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
216
backend/internal/handlers/notification_config.go
Normal file
216
backend/internal/handlers/notification_config.go
Normal file
@@ -0,0 +1,216 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/config"
|
||||
"github.com/kjannette/koin-ping/backend/internal/domain"
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
"github.com/kjannette/koin-ping/backend/internal/notifications"
|
||||
)
|
||||
|
||||
var emailRe = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
||||
|
||||
type NotificationConfigHandler struct {
|
||||
configs *models.NotificationConfigModel
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewNotificationConfigHandler(configs *models.NotificationConfigModel, cfg *config.Config) *NotificationConfigHandler {
|
||||
return &NotificationConfigHandler{configs: configs, cfg: cfg}
|
||||
}
|
||||
|
||||
func (h *NotificationConfigHandler) GetConfig(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
log.Printf("User %s getting notification config", userID)
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to get notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil {
|
||||
writeJSON(w, http.StatusOK, domain.NotificationConfig{
|
||||
UserID: userID,
|
||||
NotificationEnabled: true,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Config found")
|
||||
writeJSON(w, http.StatusOK, cfg)
|
||||
}
|
||||
|
||||
func (h *NotificationConfigHandler) UpdateConfig(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
var body struct {
|
||||
DiscordWebhookURL *string `json:"discord_webhook_url"`
|
||||
TelegramChatID *string `json:"telegram_chat_id"`
|
||||
TelegramBotToken *string `json:"telegram_bot_token"`
|
||||
Email *string `json:"email"`
|
||||
SlackWebhookURL *string `json:"slack_webhook_url"`
|
||||
NotificationEnabled *bool `json:"notification_enabled"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
log.Printf("Failed to decode notification config request body: %v", err)
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR", "Invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("User %s updating notification config", userID)
|
||||
|
||||
if body.DiscordWebhookURL == nil && body.TelegramChatID == nil &&
|
||||
body.TelegramBotToken == nil && body.Email == nil &&
|
||||
body.SlackWebhookURL == nil && body.NotificationEnabled == nil {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"At least one configuration field must be provided")
|
||||
return
|
||||
}
|
||||
|
||||
if body.DiscordWebhookURL != nil && *body.DiscordWebhookURL != "" &&
|
||||
!strings.HasPrefix(*body.DiscordWebhookURL, "https://discord.com/api/webhooks/") {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid Discord webhook URL format")
|
||||
return
|
||||
}
|
||||
|
||||
if body.SlackWebhookURL != nil && *body.SlackWebhookURL != "" &&
|
||||
!strings.HasPrefix(*body.SlackWebhookURL, "https://hooks.slack.com/") {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid Slack webhook URL format")
|
||||
return
|
||||
}
|
||||
|
||||
if body.Email != nil && *body.Email != "" && !emailRe.MatchString(*body.Email) {
|
||||
writeError(w, http.StatusBadRequest, "VALIDATION_ERROR",
|
||||
"Invalid email address format")
|
||||
return
|
||||
}
|
||||
|
||||
enabled := true
|
||||
if body.NotificationEnabled != nil {
|
||||
enabled = *body.NotificationEnabled
|
||||
}
|
||||
|
||||
cfg := domain.NotificationConfig{
|
||||
DiscordWebhookURL: body.DiscordWebhookURL,
|
||||
TelegramChatID: body.TelegramChatID,
|
||||
TelegramBotToken: body.TelegramBotToken,
|
||||
Email: body.Email,
|
||||
SlackWebhookURL: body.SlackWebhookURL,
|
||||
NotificationEnabled: enabled,
|
||||
}
|
||||
|
||||
updated, err := h.configs.UpsertConfig(r.Context(), userID, cfg)
|
||||
if err != nil {
|
||||
log.Printf("Error updating notification config: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to update notification configuration")
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Notification config updated")
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
|
||||
func (h *NotificationConfigHandler) DeleteConfig(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
log.Printf("User %s deleting notification config", userID)
|
||||
|
||||
deleted, err := h.configs.Remove(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error deleting notification config: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR",
|
||||
"Failed to delete notification configuration")
|
||||
return
|
||||
}
|
||||
|
||||
if !deleted {
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "No notification configuration found")
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Notification config deleted")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// TestChannels sends a test message to all configured notification channels.
|
||||
func (h *NotificationConfigHandler) TestChannels(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
log.Printf("User %s testing notification channels", userID)
|
||||
|
||||
cfg, err := h.configs.GetConfig(r.Context(), userID)
|
||||
if err != nil {
|
||||
log.Printf("Error getting notification config for test: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to get notification config")
|
||||
return
|
||||
}
|
||||
|
||||
if cfg == nil {
|
||||
writeError(w, http.StatusNotFound, "NOT_FOUND", "No notification configuration found")
|
||||
return
|
||||
}
|
||||
|
||||
type channelResult struct {
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
var results []channelResult
|
||||
|
||||
if cfg.DiscordWebhookURL != nil && *cfg.DiscordWebhookURL != "" {
|
||||
ok, testErr := notifications.TestDiscordWebhook(*cfg.DiscordWebhookURL)
|
||||
res := channelResult{Channel: "discord", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.TelegramBotToken != nil && *cfg.TelegramBotToken != "" &&
|
||||
cfg.TelegramChatID != nil && *cfg.TelegramChatID != "" {
|
||||
ok, testErr := notifications.TestTelegramWebhook(*cfg.TelegramBotToken, *cfg.TelegramChatID)
|
||||
res := channelResult{Channel: "telegram", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.SlackWebhookURL != nil && *cfg.SlackWebhookURL != "" {
|
||||
ok, testErr := notifications.TestSlackWebhook(*cfg.SlackWebhookURL)
|
||||
res := channelResult{Channel: "slack", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if cfg.Email != nil && *cfg.Email != "" {
|
||||
ok, testErr := notifications.TestEmailNotification(
|
||||
h.cfg.ResendAPIKey, h.cfg.EmailFrom, *cfg.Email,
|
||||
)
|
||||
res := channelResult{Channel: "email", Success: ok}
|
||||
if testErr != nil {
|
||||
res.Error = testErr.Error()
|
||||
}
|
||||
results = append(results, res)
|
||||
}
|
||||
|
||||
if len(results) == 0 {
|
||||
writeError(w, http.StatusBadRequest, "NO_CHANNELS",
|
||||
"No notification channels are configured")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{"results": results})
|
||||
}
|
||||
71
backend/internal/handlers/status.go
Normal file
71
backend/internal/handlers/status.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
)
|
||||
|
||||
// StatusHandler handles the system status endpoint.
|
||||
type StatusHandler struct {
|
||||
checkpoints *models.CheckpointModel
|
||||
}
|
||||
|
||||
// NewStatusHandler creates a new StatusHandler.
|
||||
func NewStatusHandler(checkpoints *models.CheckpointModel) *StatusHandler {
|
||||
return &StatusHandler{checkpoints: checkpoints}
|
||||
}
|
||||
|
||||
// GetStatus returns real-time system status derived from checkpoint data.
|
||||
func (h *StatusHandler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
block, checkedAt, err := h.checkpoints.GetLatestBlock(r.Context())
|
||||
if err != nil {
|
||||
log.Printf("Error querying latest block: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to get system status")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
latestBlock := 0
|
||||
lag := 0
|
||||
status := "starting"
|
||||
|
||||
if checkedAt != nil {
|
||||
lag = int(time.Since(*checkedAt).Seconds())
|
||||
if lag > 600 { //nolint:mnd
|
||||
status = "idle"
|
||||
} else {
|
||||
status = "active"
|
||||
}
|
||||
}
|
||||
|
||||
if block != nil {
|
||||
latestBlock = *block
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": status,
|
||||
"latestBlock": latestBlock,
|
||||
"lag": lag,
|
||||
"lastCheckedAt": checkedAtStr(checkedAt),
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
func checkedAtStr(t *time.Time) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
func HealthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339),
|
||||
"service": "koin-ping-backend",
|
||||
})
|
||||
}
|
||||
254
backend/internal/handlers/stripe.go
Normal file
254
backend/internal/handlers/stripe.go
Normal file
@@ -0,0 +1,254 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/stripe/stripe-go/v82"
|
||||
checkoutsession "github.com/stripe/stripe-go/v82/checkout/session"
|
||||
"github.com/stripe/stripe-go/v82/webhook"
|
||||
|
||||
"github.com/kjannette/koin-ping/backend/internal/config"
|
||||
"github.com/kjannette/koin-ping/backend/internal/middleware"
|
||||
"github.com/kjannette/koin-ping/backend/internal/models"
|
||||
)
|
||||
|
||||
const webhookMaxBodyBytes = 65536
|
||||
|
||||
type StripeHandler struct {
|
||||
users *models.UserModel
|
||||
cfg *config.Config
|
||||
}
|
||||
|
||||
func NewStripeHandler(users *models.UserModel, cfg *config.Config) *StripeHandler {
|
||||
stripe.Key = cfg.StripeSecretKey
|
||||
return &StripeHandler{users: users, cfg: cfg}
|
||||
}
|
||||
|
||||
// CreateCheckoutSession creates a Stripe Checkout session for the monthly subscription.
|
||||
func (h *StripeHandler) CreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
user, err := h.users.GetByID(r.Context(), userID)
|
||||
if err != nil || user == nil {
|
||||
log.Printf("Failed to get user %s: %v", userID, err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to load user")
|
||||
return
|
||||
}
|
||||
|
||||
params := &stripe.CheckoutSessionParams{
|
||||
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
|
||||
LineItems: []*stripe.CheckoutSessionLineItemParams{
|
||||
{
|
||||
Price: stripe.String(h.cfg.StripePriceID),
|
||||
Quantity: stripe.Int64(1),
|
||||
},
|
||||
},
|
||||
SuccessURL: stripe.String(h.cfg.FrontendURL + "/subscribe?payment=success&session_id={CHECKOUT_SESSION_ID}"),
|
||||
CancelURL: stripe.String(h.cfg.FrontendURL + "/subscribe?payment=cancelled"),
|
||||
ClientReferenceID: stripe.String(userID),
|
||||
CustomerEmail: stripe.String(user.Email),
|
||||
}
|
||||
|
||||
if user.StripeCustomerID != nil && *user.StripeCustomerID != "" {
|
||||
params.Customer = user.StripeCustomerID
|
||||
params.CustomerEmail = nil
|
||||
}
|
||||
|
||||
s, err := checkoutsession.New(params)
|
||||
if err != nil {
|
||||
log.Printf("Failed to create Stripe checkout session: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, "STRIPE_ERROR", "Failed to create checkout session")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]string{"url": s.URL})
|
||||
}
|
||||
|
||||
// GetSubscriptionStatus returns the current user's subscription state.
|
||||
func (h *StripeHandler) GetSubscriptionStatus(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
user, err := h.users.GetByID(r.Context(), userID)
|
||||
if err != nil || user == nil {
|
||||
log.Printf("Failed to get user %s: %v", userID, err)
|
||||
writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", "Failed to load user")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"subscription_status": user.SubscriptionStatus,
|
||||
"subscription_created_at": user.SubscriptionCreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
// VerifyCheckoutSession retrieves a completed checkout session from Stripe,
|
||||
// confirms payment, and activates the user's subscription in the database.
|
||||
// This is the primary activation path; webhooks serve as a backup.
|
||||
func (h *StripeHandler) VerifyCheckoutSession(w http.ResponseWriter, r *http.Request) {
|
||||
userID := middleware.GetUserID(r.Context())
|
||||
|
||||
var body struct {
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.SessionID == "" {
|
||||
writeError(w, http.StatusBadRequest, "BAD_REQUEST", "Missing session_id")
|
||||
return
|
||||
}
|
||||
|
||||
s, err := checkoutsession.Get(body.SessionID, nil)
|
||||
if err != nil {
|
||||
log.Printf("Failed to retrieve checkout session %s: %v", body.SessionID, err)
|
||||
writeError(w, http.StatusBadRequest, "STRIPE_ERROR", "Invalid checkout session")
|
||||
return
|
||||
}
|
||||
|
||||
if s.ClientReferenceID != userID {
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN", "Session does not belong to this user")
|
||||
return
|
||||
}
|
||||
|
||||
if s.PaymentStatus != stripe.CheckoutSessionPaymentStatusPaid {
|
||||
writeError(w, http.StatusBadRequest, "PAYMENT_INCOMPLETE", "Payment has not been completed")
|
||||
return
|
||||
}
|
||||
|
||||
customerID := ""
|
||||
if s.Customer != nil {
|
||||
customerID = s.Customer.ID
|
||||
}
|
||||
subscriptionID := ""
|
||||
if s.Subscription != nil {
|
||||
subscriptionID = s.Subscription.ID
|
||||
}
|
||||
|
||||
if customerID != "" {
|
||||
if err := h.users.UpdateStripeCustomer(r.Context(), userID, customerID); err != nil {
|
||||
log.Printf("VerifyCheckout: failed to save customer ID: %v", err)
|
||||
}
|
||||
}
|
||||
if subscriptionID != "" && customerID != "" {
|
||||
if err := h.users.ActivateSubscription(r.Context(), customerID, subscriptionID, "active"); err != nil {
|
||||
log.Printf("VerifyCheckout: failed to activate subscription: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Checkout verified for user %s, customer %s, subscription %s", userID, customerID, subscriptionID)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"subscription_status": "active"})
|
||||
}
|
||||
|
||||
// HandleWebhook processes incoming Stripe webhook events.
|
||||
// This endpoint must NOT require authentication (Stripe calls it directly).
|
||||
func (h *StripeHandler) HandleWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
payload, err := io.ReadAll(io.LimitReader(r.Body, webhookMaxBodyBytes))
|
||||
if err != nil {
|
||||
log.Printf("Error reading webhook body: %v", err)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
sig := r.Header.Get("Stripe-Signature")
|
||||
event, err := webhook.ConstructEvent(payload, sig, h.cfg.StripeWebhookSecret)
|
||||
if err != nil {
|
||||
log.Printf("Webhook signature verification failed: %v", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
switch event.Type {
|
||||
case "checkout.session.completed":
|
||||
h.handleCheckoutCompleted(r, event)
|
||||
case "customer.subscription.updated":
|
||||
h.handleSubscriptionUpdated(r, event)
|
||||
case "customer.subscription.deleted":
|
||||
h.handleSubscriptionDeleted(r, event)
|
||||
default:
|
||||
log.Printf("Unhandled Stripe event type: %s", event.Type)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (h *StripeHandler) handleCheckoutCompleted(r *http.Request, event stripe.Event) {
|
||||
var session stripe.CheckoutSession
|
||||
if err := json.Unmarshal(event.Data.Raw, &session); err != nil {
|
||||
log.Printf("Error parsing checkout session: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
userID := session.ClientReferenceID
|
||||
if userID == "" {
|
||||
log.Println("Checkout session missing client_reference_id")
|
||||
return
|
||||
}
|
||||
|
||||
customerID := ""
|
||||
if session.Customer != nil {
|
||||
customerID = session.Customer.ID
|
||||
}
|
||||
subscriptionID := ""
|
||||
if session.Subscription != nil {
|
||||
subscriptionID = session.Subscription.ID
|
||||
}
|
||||
|
||||
if customerID != "" {
|
||||
if err := h.users.UpdateStripeCustomer(r.Context(), userID, customerID); err != nil {
|
||||
log.Printf("Failed to save Stripe customer ID: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if subscriptionID != "" && customerID != "" {
|
||||
if err := h.users.ActivateSubscription(r.Context(), customerID, subscriptionID, "active"); err != nil {
|
||||
log.Printf("Failed to activate subscription: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("Checkout completed for user %s, customer %s, subscription %s", userID, customerID, subscriptionID)
|
||||
}
|
||||
|
||||
func (h *StripeHandler) handleSubscriptionUpdated(r *http.Request, event stripe.Event) {
|
||||
var sub stripe.Subscription
|
||||
if err := json.Unmarshal(event.Data.Raw, &sub); err != nil {
|
||||
log.Printf("Error parsing subscription update: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
customerID := ""
|
||||
if sub.Customer != nil {
|
||||
customerID = sub.Customer.ID
|
||||
}
|
||||
if customerID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
status := string(sub.Status)
|
||||
if err := h.users.ActivateSubscription(r.Context(), customerID, sub.ID, status); err != nil {
|
||||
log.Printf("Failed to update subscription status: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Subscription %s updated to %s for customer %s", sub.ID, status, customerID)
|
||||
}
|
||||
|
||||
func (h *StripeHandler) handleSubscriptionDeleted(r *http.Request, event stripe.Event) {
|
||||
var sub stripe.Subscription
|
||||
if err := json.Unmarshal(event.Data.Raw, &sub); err != nil {
|
||||
log.Printf("Error parsing subscription deletion: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
customerID := ""
|
||||
if sub.Customer != nil {
|
||||
customerID = sub.Customer.ID
|
||||
}
|
||||
if customerID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.users.UpdateSubscriptionStatus(r.Context(), customerID, "canceled"); err != nil {
|
||||
log.Printf("Failed to mark subscription canceled: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("Subscription canceled for customer %s", customerID)
|
||||
}
|
||||
Reference in New Issue
Block a user