Fix device registration error mapping for invalid user IDs.
Validate device registration input and translate devices_user_fk violations into a clear bad-request response so invalid auth contexts no longer return opaque 500 errors. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
6a4fe68628
commit
b2a72c2f6e
|
|
@ -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),
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user