feat(notifications): align subscription payloads
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
)
|
||||
|
||||
@@ -22,14 +25,14 @@ func NewNotificationSubscriptionHandler(svc *service.NotificationSubscriptionSer
|
||||
// POST /api/v1/notification_subscriptions
|
||||
// Chatwoot: requires identifier, subscription_attributes, subscription_type
|
||||
func (h *NotificationSubscriptionHandler) Create(c *gin.Context) {
|
||||
userID, exists := c.Get("current_user_id")
|
||||
if !exists {
|
||||
userID := getUserID(c)
|
||||
if userID == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
var req service.CreateSubscriptionRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindJSONWrappedOrRaw(c, "notification_subscription", &req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
@@ -40,35 +43,62 @@ func (h *NotificationSubscriptionHandler) Create(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
sub, err := h.svc.Create(c.Request.Context(), userID.(uint), &req)
|
||||
sub, err := h.svc.Create(c.Request.Context(), userID, &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, sub)
|
||||
c.JSON(http.StatusOK, notificationSubscriptionPayloadFromModel(sub))
|
||||
}
|
||||
|
||||
// Destroy removes a notification subscription.
|
||||
// DELETE /api/v1/notification_subscriptions/:identifier
|
||||
// Chatwoot: finds by identifier and deletes
|
||||
func (h *NotificationSubscriptionHandler) Destroy(c *gin.Context) {
|
||||
userID, exists := c.Get("current_user_id")
|
||||
if !exists {
|
||||
userID := getUserID(c)
|
||||
if userID == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
|
||||
identifier := c.Param("identifier")
|
||||
if identifier == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "identifier is required"})
|
||||
return
|
||||
pushToken := c.Query("push_token")
|
||||
if pushToken == "" {
|
||||
pushToken = c.Param("identifier")
|
||||
}
|
||||
if pushToken == "" {
|
||||
pushToken = c.PostForm("push_token")
|
||||
}
|
||||
if pushToken == "" && c.Request.Body != nil {
|
||||
var body struct {
|
||||
PushToken string `json:"push_token"`
|
||||
}
|
||||
_ = c.ShouldBindJSON(&body)
|
||||
pushToken = body.PushToken
|
||||
}
|
||||
|
||||
if err := h.svc.Destroy(c.Request.Context(), userID.(uint), identifier); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
_ = h.svc.Destroy(c.Request.Context(), userID, pushToken)
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{})
|
||||
}
|
||||
type notificationSubscriptionDTO struct {
|
||||
ID uint `json:"id"`
|
||||
Identifier string `json:"identifier"`
|
||||
SubscriptionAttributes json.RawMessage `json:"subscription_attributes"`
|
||||
SubscriptionType string `json:"subscription_type"`
|
||||
UserID uint `json:"user_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func notificationSubscriptionPayloadFromModel(sub *model.NotificationSubscription) notificationSubscriptionDTO {
|
||||
return notificationSubscriptionDTO{
|
||||
ID: sub.ID,
|
||||
Identifier: sub.Identifier,
|
||||
SubscriptionAttributes: sub.SubscriptionAttributes,
|
||||
SubscriptionType: sub.SubscriptionType.String(),
|
||||
UserID: sub.UserID,
|
||||
CreatedAt: sub.CreatedAt,
|
||||
UpdatedAt: sub.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupNotificationSubscriptionHandlerTest(t *testing.T, userID uint) (*gin.Engine, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(&model.User{}, &model.NotificationSubscription{}))
|
||||
|
||||
handler := NewNotificationSubscriptionHandler(service.NewNotificationSubscriptionService(repository.NewNotificationSubscriptionRepo(db)))
|
||||
router := gin.New()
|
||||
router.Use(func(c *gin.Context) {
|
||||
c.Set("user_id", userID)
|
||||
c.Next()
|
||||
})
|
||||
router.POST("/api/v1/notification_subscriptions", handler.Create)
|
||||
router.DELETE("/api/v1/notification_subscriptions", handler.Destroy)
|
||||
router.DELETE("/api/v1/notification_subscriptions/:identifier", handler.Destroy)
|
||||
return router, db
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionCreateAcceptsFrontendPayload(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
body := `{"subscription_type":"browser_push","subscription_attributes":{"endpoint":"https://push.example/sub","p256dh":"key","auth":"secret"}}`
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/notification_subscriptions", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload), w.Body.String())
|
||||
require.NotContains(t, payload, "success")
|
||||
require.NotContains(t, payload, "data")
|
||||
require.Equal(t, "https://push.example/sub", payload["identifier"])
|
||||
require.Equal(t, "browser_push", payload["subscription_type"])
|
||||
require.Equal(t, float64(7), payload["user_id"])
|
||||
|
||||
var sub model.NotificationSubscription
|
||||
require.NoError(t, db.First(&sub).Error)
|
||||
require.Equal(t, uint(7), sub.UserID)
|
||||
require.Equal(t, "https://push.example/sub", sub.Identifier)
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionCreateAcceptsRailsWrapperAndUpdatesExisting(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 11)
|
||||
existing := model.NotificationSubscription{
|
||||
Identifier: "device-1",
|
||||
UserID: 2,
|
||||
SubscriptionType: model.NotificationSubFCM,
|
||||
SubscriptionAttributes: json.RawMessage(`{"device_id":"device-1","push_token":"old"}`),
|
||||
}
|
||||
require.NoError(t, db.Create(&existing).Error)
|
||||
body := `{"notification_subscription":{"subscription_type":"fcm","subscription_attributes":{"device_id":"device-1","push_token":"new"}}}`
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/notification_subscriptions", bytes.NewBufferString(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
var sub model.NotificationSubscription
|
||||
require.NoError(t, db.First(&sub, existing.ID).Error)
|
||||
require.Equal(t, uint(11), sub.UserID)
|
||||
require.JSONEq(t, `{"device_id":"device-1","push_token":"new"}`, string(sub.SubscriptionAttributes))
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionDestroyUsesPushTokenAndReturnsEmptyOK(t *testing.T) {
|
||||
router, db := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
sub := model.NotificationSubscription{
|
||||
Identifier: "https://push.example/sub",
|
||||
UserID: 7,
|
||||
SubscriptionType: model.NotificationSubBrowserPush,
|
||||
SubscriptionAttributes: json.RawMessage(`{"endpoint":"https://push.example/sub","p256dh":"key","auth":"secret"}`),
|
||||
}
|
||||
require.NoError(t, db.Create(&sub).Error)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/notification_subscriptions?push_token=https%3A%2F%2Fpush.example%2Fsub", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Empty(t, w.Body.String())
|
||||
var count int64
|
||||
require.NoError(t, db.Model(&model.NotificationSubscription{}).Where("id = ?", sub.ID).Count(&count).Error)
|
||||
require.Equal(t, int64(0), count)
|
||||
}
|
||||
|
||||
func TestNotificationSubscriptionDestroyMissingTokenStillOK(t *testing.T) {
|
||||
router, _ := setupNotificationSubscriptionHandlerTest(t, 7)
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/notification_subscriptions", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Empty(t, w.Body.String())
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"gorm.io/gorm"
|
||||
@@ -21,6 +22,11 @@ func (r *NotificationSubscriptionRepo) Create(ctx context.Context, sub *model.No
|
||||
return r.db.WithContext(ctx).Create(sub).Error
|
||||
}
|
||||
|
||||
// Save inserts or updates a subscription.
|
||||
func (r *NotificationSubscriptionRepo) Save(ctx context.Context, sub *model.NotificationSubscription) error {
|
||||
return r.db.WithContext(ctx).Save(sub).Error
|
||||
}
|
||||
|
||||
// FindByID retrieves a subscription by ID.
|
||||
func (r *NotificationSubscriptionRepo) FindByID(ctx context.Context, id uint) (*model.NotificationSubscription, error) {
|
||||
var sub model.NotificationSubscription
|
||||
@@ -35,6 +41,29 @@ func (r *NotificationSubscriptionRepo) FindByUserID(ctx context.Context, userID
|
||||
return subs, err
|
||||
}
|
||||
|
||||
// FindByUserIDAndPushToken finds the Chatwoot destroy target by push_token.
|
||||
func (r *NotificationSubscriptionRepo) FindByUserIDAndPushToken(ctx context.Context, userID uint, pushToken string) (*model.NotificationSubscription, error) {
|
||||
subs, err := r.FindByUserID(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range subs {
|
||||
if subs[i].Identifier == pushToken {
|
||||
return &subs[i], nil
|
||||
}
|
||||
var attrs map[string]any
|
||||
if err := json.Unmarshal(subs[i].SubscriptionAttributes, &attrs); err == nil {
|
||||
if value, _ := attrs["push_token"].(string); value == pushToken {
|
||||
return &subs[i], nil
|
||||
}
|
||||
if value, _ := attrs["endpoint"].(string); value == pushToken {
|
||||
return &subs[i], nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil, gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
// FindByIdentifier retrieves a subscription by its unique identifier.
|
||||
func (r *NotificationSubscriptionRepo) FindByIdentifier(ctx context.Context, identifier string) (*model.NotificationSubscription, error) {
|
||||
var sub model.NotificationSubscription
|
||||
@@ -52,4 +81,4 @@ func (r *NotificationSubscriptionRepo) DeleteByUserIDAndIdentifier(ctx context.C
|
||||
return r.db.WithContext(ctx).
|
||||
Where("user_id = ? AND identifier = ?", userID, identifier).
|
||||
Delete(&model.NotificationSubscription{}).Error
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,6 +609,7 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
// Notification subscription routes — user-scoped, browser_push/fcm subscription management
|
||||
// Reference: Chatwoot resource :notification_subscriptions, only: [:create, :destroy]
|
||||
g.POST("/notification_subscriptions", h.NotificationSubscription.Create)
|
||||
g.DELETE("/notification_subscriptions", h.NotificationSubscription.Destroy)
|
||||
g.DELETE("/notification_subscriptions/:identifier", h.NotificationSubscription.Destroy)
|
||||
|
||||
// SSO session management routes — user-scoped, authenticated (M13)
|
||||
@@ -1632,6 +1633,7 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
notifSubs := accountScoped.Group("/notification_subscriptions")
|
||||
{
|
||||
notifSubs.POST("/", h.NotificationSubscription.Create)
|
||||
notifSubs.DELETE("/", h.NotificationSubscription.Destroy)
|
||||
notifSubs.DELETE("/:identifier", h.NotificationSubscription.Destroy)
|
||||
}
|
||||
|
||||
|
||||
@@ -23,14 +23,26 @@ func NewNotificationSubscriptionService(repo *repository.NotificationSubscriptio
|
||||
|
||||
// CreateSubscriptionRequest matches Chatwoot's create action payload.
|
||||
type CreateSubscriptionRequest struct {
|
||||
Identifier string `json:"identifier" binding:"required"`
|
||||
SubscriptionAttributes json.RawMessage `json:"subscription_attributes" binding:"required"`
|
||||
SubscriptionType string `json:"subscription_type" binding:"required"` // "browser_push" or "fcm"
|
||||
Identifier string `json:"identifier"`
|
||||
SubscriptionAttributes json.RawMessage `json:"subscription_attributes"`
|
||||
SubscriptionType string `json:"subscription_type"` // "browser_push" or "fcm"
|
||||
}
|
||||
|
||||
// Create adds a new notification subscription for a user.
|
||||
// Chatwoot behavior: validates identifier uniqueness, creates subscription with type enum.
|
||||
func (s *NotificationSubscriptionService) Create(ctx context.Context, userID uint, req *CreateSubscriptionRequest) (*model.NotificationSubscription, error) {
|
||||
if req.SubscriptionType == "" {
|
||||
return nil, fmt.Errorf("subscription_type is required")
|
||||
}
|
||||
if len(req.SubscriptionAttributes) == 0 {
|
||||
return nil, fmt.Errorf("subscription_attributes is required")
|
||||
}
|
||||
identifier, err := notificationSubscriptionIdentifier(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Identifier = identifier
|
||||
|
||||
// Check for duplicate identifier
|
||||
existing, err := s.repo.FindByIdentifier(ctx, req.Identifier)
|
||||
if err == nil && existing != nil {
|
||||
@@ -38,7 +50,7 @@ func (s *NotificationSubscriptionService) Create(ctx context.Context, userID uin
|
||||
existing.SubscriptionAttributes = req.SubscriptionAttributes
|
||||
existing.SubscriptionType = model.NotificationSubscriptionTypeFromString(req.SubscriptionType)
|
||||
existing.UserID = userID
|
||||
if err := s.repo.Create(ctx, existing); err != nil {
|
||||
if err := s.repo.Save(ctx, existing); err != nil {
|
||||
applogger.L().Errorf("NotificationSubscription Create update: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
@@ -47,10 +59,10 @@ func (s *NotificationSubscriptionService) Create(ctx context.Context, userID uin
|
||||
|
||||
subType := model.NotificationSubscriptionTypeFromString(req.SubscriptionType)
|
||||
sub := &model.NotificationSubscription{
|
||||
Identifier: req.Identifier,
|
||||
Identifier: req.Identifier,
|
||||
SubscriptionAttributes: req.SubscriptionAttributes,
|
||||
SubscriptionType: subType,
|
||||
UserID: userID,
|
||||
SubscriptionType: subType,
|
||||
UserID: userID,
|
||||
}
|
||||
|
||||
if err := s.repo.Create(ctx, sub); err != nil {
|
||||
@@ -63,14 +75,12 @@ func (s *NotificationSubscriptionService) Create(ctx context.Context, userID uin
|
||||
// Destroy removes a notification subscription.
|
||||
// Chatwoot behavior: finds by identifier and deletes.
|
||||
func (s *NotificationSubscriptionService) Destroy(ctx context.Context, userID uint, identifier string) error {
|
||||
// Chatwoot finds by identifier first, then deletes
|
||||
sub, err := s.repo.FindByIdentifier(ctx, identifier)
|
||||
sub, err := s.repo.FindByUserIDAndPushToken(ctx, userID, identifier)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("NotificationSubscription Destroy find: %v", err)
|
||||
return err
|
||||
return nil
|
||||
}
|
||||
if sub == nil || sub.UserID != userID {
|
||||
return fmt.Errorf("notification subscription not found")
|
||||
if sub == nil {
|
||||
return nil
|
||||
}
|
||||
return s.repo.Delete(ctx, sub.ID)
|
||||
}
|
||||
@@ -94,9 +104,33 @@ func ValidateSubscriptionAttributes(subType string, attrs json.RawMessage) error
|
||||
return fmt.Errorf("missing required field: endpoint, p256dh, auth")
|
||||
}
|
||||
case "fcm":
|
||||
if m["token"] == nil {
|
||||
if m["token"] == nil && m["device_id"] == nil && m["push_token"] == nil {
|
||||
return fmt.Errorf("missing required field: token")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func notificationSubscriptionIdentifier(req *CreateSubscriptionRequest) (string, error) {
|
||||
if req.Identifier != "" {
|
||||
return req.Identifier, nil
|
||||
}
|
||||
var attrs map[string]any
|
||||
if err := json.Unmarshal(req.SubscriptionAttributes, &attrs); err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch req.SubscriptionType {
|
||||
case "browser_push":
|
||||
if endpoint, _ := attrs["endpoint"].(string); endpoint != "" {
|
||||
return endpoint, nil
|
||||
}
|
||||
case "fcm":
|
||||
if deviceID, _ := attrs["device_id"].(string); deviceID != "" {
|
||||
return deviceID, nil
|
||||
}
|
||||
if pushToken, _ := attrs["push_token"].(string); pushToken != "" {
|
||||
return pushToken, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("identifier is required")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user