diff --git a/internal/web_server/handlers/notification_handler.go b/internal/web_server/handlers/notification_handler.go index 410666f..9f98cc7 100644 --- a/internal/web_server/handlers/notification_handler.go +++ b/internal/web_server/handlers/notification_handler.go @@ -6,6 +6,7 @@ import ( "bufio" "context" "encoding/json" + "errors" "fmt" "io" "net" @@ -16,6 +17,7 @@ import ( "github.com/gofiber/fiber/v2" "github.com/gorilla/websocket" + "github.com/jackc/pgx/v5/pgconn" "github.com/resend/resend-go/v2" "go.uber.org/zap" ) @@ -111,7 +113,7 @@ type hijackResponseWriter struct { h http.Header } -func (w *hijackResponseWriter) Header() http.Header { return w.h } +func (w *hijackResponseWriter) Header() http.Header { return w.h } func (w *hijackResponseWriter) WriteHeader(statusCode int) {} func (w *hijackResponseWriter) Write(b []byte) (int, error) { return w.conn.Write(b) } func (w *hijackResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { @@ -662,6 +664,12 @@ func (h *Handler) RegisterDeviceToken(c *fiber.Ctx) error { ) return fiber.NewError(fiber.StatusBadRequest, "Invalid request body") } + if valErrs, ok := h.validator.Validate(c, req); !ok { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Validation failed", + Error: firstValidationError(valErrs), + }) + } userID, ok := c.Locals("user_id").(int64) if !ok || userID == 0 { @@ -673,6 +681,14 @@ func (h *Handler) RegisterDeviceToken(c *fiber.Ctx) error { } if err := h.userSvc.RegisterDevice(c.Context(), userID, req.DeviceToken, req.Platform); err != nil { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23503" && pgErr.ConstraintName == "devices_user_fk" { + return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{ + Message: "Invalid authenticated user", + Error: "authenticated user does not exist in users table", + }) + } + h.mongoLoggerSvc.Error("[NotificationHandler.RegisterDeviceToken] Failed to register device token", zap.Int64("userID", userID), zap.String("platform", req.Platform),