FIX: de-duplicate push subscriptions - ensure unique user/key

This commit is contained in:
Jeff Wong 2018-05-08 15:14:58 -07:00
parent 2c4da30f1b
commit 7f1f697e97
2 changed files with 55 additions and 1 deletions

View File

@ -33,7 +33,13 @@ class PushNotificationPusher
end end
def self.subscribe(user, subscription, send_confirmation) def self.subscribe(user, subscription, send_confirmation)
subscriptions = PushSubscription.where(user: user, data: subscription.to_json)
if subscriptions.length > 1
subscriptions.destroy_all
PushSubscription.create user: user, data: subscription.to_json 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" if send_confirmation == "true"
message = { message = {
title: I18n.t("discourse_push_notifications.popup.confirm_title", title: I18n.t("discourse_push_notifications.popup.confirm_title",

View File

@ -41,6 +41,54 @@ describe PushNotificationController do
expect(user.push_subscriptions.count).to eq(1) expect(user.push_subscriptions.count).to eq(1)
end 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 it "should unsubscribe with existing subscription" do
sub = { endpoint: "endpoint", keys: { p256dh: "256dh", auth: "auth" } } sub = { endpoint: "endpoint", keys: { p256dh: "256dh", auth: "auth" } }
PushSubscription.create!(user: user, data: sub.to_json) PushSubscription.create!(user: user, data: sub.to_json)