From 7f1f697e97673702011ec538aaf7ff858c371d4b Mon Sep 17 00:00:00 2001 From: Jeff Wong Date: Tue, 8 May 2018 15:14:58 -0700 Subject: [PATCH] FIX: de-duplicate push subscriptions - ensure unique user/key --- app/services/push_notification_pusher.rb | 8 +++- .../push_notification_controller_spec.rb | 48 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/app/services/push_notification_pusher.rb b/app/services/push_notification_pusher.rb index a9b4ab0f2af..cc7a9cb8978 100644 --- a/app/services/push_notification_pusher.rb +++ b/app/services/push_notification_pusher.rb @@ -33,7 +33,13 @@ class PushNotificationPusher end def self.subscribe(user, subscription, send_confirmation) - PushSubscription.create user: user, data: subscription.to_json + subscriptions = PushSubscription.where(user: user, data: subscription.to_json) + if subscriptions.length > 1 + subscriptions.destroy_all + PushSubscription.create user: user, data: subscription.to_json + elsif subscriptions.length == 0 + PushSubscription.create user: user, data: subscription.to_json + end if send_confirmation == "true" message = { title: I18n.t("discourse_push_notifications.popup.confirm_title", diff --git a/spec/requests/push_notification_controller_spec.rb b/spec/requests/push_notification_controller_spec.rb index ef89ff9ed9a..5c0f9dc03cb 100644 --- a/spec/requests/push_notification_controller_spec.rb +++ b/spec/requests/push_notification_controller_spec.rb @@ -41,6 +41,54 @@ describe PushNotificationController do expect(user.push_subscriptions.count).to eq(1) end + it "should fix duplicate subscriptions" do + subscription = { + endpoint: "endpoint", + keys: { + p256dh: "256dh", + auth: "auth" + } + } + PushSubscription.create user: user, data: subscription.to_json + post '/push_notifications/subscribe.json', params: { + username: user.username, + subscription: subscription, + send_confirmation: false + } + + expect(response.status).to eq(200) + expect(user.push_subscriptions.count).to eq(1) + end + + it "should not create duplicate subscriptions" do + post '/push_notifications/subscribe.json', params: { + username: user.username, + subscription: { + endpoint: "endpoint", + keys: { + p256dh: "256dh", + auth: "auth" + } + }, + send_confirmation: false + } + + post '/push_notifications/subscribe.json', params: { + username: user.username, + subscription: { + endpoint: "endpoint", + keys: { + p256dh: "256dh", + auth: "auth" + } + }, + send_confirmation: false + } + + expect(response.status).to eq(200) + expect(user.push_subscriptions.count).to eq(1) + end + it "should unsubscribe with existing subscription" do sub = { endpoint: "endpoint", keys: { p256dh: "256dh", auth: "auth" } } PushSubscription.create!(user: user, data: sub.to_json)