A platform for community discussion. Free, open, simple.
FIX: only clear current device push subscription on logout (#39266)
Rafael dos Santos Silva470a91a35dfd
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex 76469da941c..63cb571529c 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -178,6 +178,7 @@ class Admin::UsersController < Admin::StaffControllerdef log_outif @user@user.user_auth_tokens.destroy_all+ PushNotificationPusher.clear_subscriptions(@user)@user.logged_outrender json: success_jsonelsediff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rbindex 5683c259d2e..bae0068219a 100644--- a/app/controllers/session_controller.rb+++ b/app/controllers/session_controller.rb@@ -700,8 +700,17 @@ class SessionController < ApplicationController# `redirect_url` might have been updated by a `before_session_destroy` listenerredirect_url = data[:redirect_url]+ push_subscription =+ begin+ if params[:push_subscription].is_a?(ActionController::Parameters)+ params.require(:push_subscription).permit(:endpoint, keys: %i[p256dh auth])+ end+ rescue StandardError+ nil # best-effort: malformed push_subscription should never block logout+ end+reset_session- log_off_user+ log_off_user(push_subscription:)if request.xhr?render json: { redirect_url: }diff --git a/app/services/push_notification_pusher.rb b/app/services/push_notification_pusher.rbindex fd21a785117..d10d5054f23 100644--- a/app/services/push_notification_pusher.rb+++ b/app/services/push_notification_pusher.rb@@ -97,7 +97,7 @@ class PushNotificationPusherenddef self.unsubscribe(user, subscription)- PushSubscription.find_by(user: user, data: subscription.to_json)&.destroy!+ PushSubscription.where(user: user, data: subscription.to_json).delete_allenddef self.get_badgediff --git a/app/services/user_suspender.rb b/app/services/user_suspender.rbindex 8488b0dadb7..ad18291a93d 100644--- a/app/services/user_suspender.rb+++ b/app/services/user_suspender.rb@@ -29,6 +29,7 @@ class UserSuspenderpost_id: @post_id,)end+ PushNotificationPusher.clear_subscriptions(@user)@user.logged_outif @message.present?diff --git a/config/initializers/100-push-notifications.rb b/config/initializers/100-push-notifications.rbindex 1261c465c6a..cf4d8e6dab3 100644--- a/config/initializers/100-push-notifications.rb+++ b/config/initializers/100-push-notifications.rb@@ -23,6 +23,4 @@ Rails.application.config.to_prepare doPushSubscription.delete_all if ActiveRecord::Base.connection.table_exists?(:push_subscriptions)end-- DiscourseEvent.on(:user_logged_out) { |user| PushNotificationPusher.clear_subscriptions(user) }enddiff --git a/frontend/discourse/app/lib/push-notifications.js b/frontend/discourse/app/lib/push-notifications.jsindex f69b2e4514a..a79752506ca 100644--- a/frontend/discourse/app/lib/push-notifications.js+++ b/frontend/discourse/app/lib/push-notifications.js@@ -105,6 +105,25 @@ export function subscribe(callback, applicationServerKey) {});}+export async function getCurrentPushSubscription() {+ if (!("serviceWorker" in navigator) || !("PushManager" in window)) {+ return null;+ }++ try {+ const registration = await navigator.serviceWorker.getRegistration();+ if (!registration) {+ return null;+ }+ const subscription = await registration.pushManager.getSubscription();+ return subscription ? subscription.toJSON() : null;+ } catch (e) {+ // eslint-disable-next-line no-console+ console.error(e);+ return null;+ }+}+export function unsubscribe(user, callback) {if (!isPushNotificationsSupported()) {return;diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.jsindex 3ffb95b5b17..91a15fa35d7 100644--- a/frontend/discourse/app/models/user.js+++ b/frontend/discourse/app/models/user.js@@ -401,8 +401,12 @@ export default class User extends RestModel.extend(Evented) {return this.staff && this.get("has_new_upcoming_changes");}- destroySession() {- return ajax(`/session/${this.username}`, { type: "DELETE" });+ destroySession(pushSubscription) {+ const data = {};+ if (pushSubscription) {+ data.push_subscription = pushSubscription;+ }+ return ajax(`/session/${this.username}`, { type: "DELETE", data });}@computed("username_lower")diff --git a/frontend/discourse/app/routes/application.js b/frontend/discourse/app/routes/application.jsindex 102e4bbecfa..2818dd58303 100644--- a/frontend/discourse/app/routes/application.js+++ b/frontend/discourse/app/routes/application.js@@ -8,6 +8,7 @@ import EmbedMode from "discourse/lib/embed-mode";import getURL from "discourse/lib/get-url";import logout from "discourse/lib/logout";import mobile from "discourse/lib/mobile";+import { getCurrentPushSubscription } from "discourse/lib/push-notifications";import identifySource, { consolePrefix } from "discourse/lib/source-identifier";import DiscourseURL from "discourse/lib/url";import Category from "discourse/models/category";@@ -82,15 +83,15 @@ export default class ApplicationRoute extends DiscourseRoute {}@action- logout() {+ async logout() {const { isReadOnly, isStaffWritesOnly } = this.site;if (isReadOnly && !isStaffWritesOnly) {this.dialog.alert(i18n("read_only_mode.logout_disabled"));} else if (this.currentUser) {- this.currentUser- .destroySession()- .then((response) => logout({ redirect: response["redirect_url"] }));+ const pushSubscription = await getCurrentPushSubscription();+ const response = await this.currentUser.destroySession(pushSubscription);+ logout({ redirect: response["redirect_url"] });}}diff --git a/lib/auth/current_user_provider.rb b/lib/auth/current_user_provider.rbindex 310070a9628..a555c6da83e 100644--- a/lib/auth/current_user_provider.rb+++ b/lib/auth/current_user_provider.rb@@ -50,7 +50,7 @@ class Auth::CurrentUserProviderraise NotImplementedErrorend- def log_off_user(session, cookie_jar)+ def log_off_user(session, cookie_jar, push_subscription: nil)raise NotImplementedErrorendenddiff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rbindex 75ace188123..f01d584bfd5 100644--- a/lib/auth/default_current_user_provider.rb+++ b/lib/auth/default_current_user_provider.rb@@ -335,7 +335,7 @@ class Auth::DefaultCurrentUserProviderendend- def log_off_user(session, cookie_jar)+ def log_off_user(session, cookie_jar, push_subscription: nil)user = current_userif SiteSetting.log_out_strict && user@@ -346,9 +346,11 @@ class Auth::DefaultCurrentUserProvidercookie_jar.delete("__profilin")end+ PushNotificationPusher.clear_subscriptions(user)user.logged_outelsif user && @user_token@user_token.destroy+ PushNotificationPusher.unsubscribe(user, push_subscription) if push_subscriptionDiscourseEvent.trigger(:user_logged_out, user)enddiff --git a/lib/current_user.rb b/lib/current_user.rbindex 1dce1bd82e6..e5d94513a0a 100644--- a/lib/current_user.rb+++ b/lib/current_user.rb@@ -19,8 +19,8 @@ module CurrentUseruser.logged_inend- def log_off_user- current_user_provider.log_off_user(session, cookies)+ def log_off_user(push_subscription: nil)+ current_user_provider.log_off_user(session, cookies, push_subscription:)enddef start_impersonating_user(user)diff --git a/spec/lib/auth/default_current_user_provider_spec.rb b/spec/lib/auth/default_current_user_provider_spec.rbindex 7e02c131b40..0289d0d599f 100644--- a/spec/lib/auth/default_current_user_provider_spec.rb+++ b/spec/lib/auth/default_current_user_provider_spec.rb@@ -765,6 +765,49 @@ RSpec.describe Auth::DefaultCurrentUserProvider doDiscourseEvent.off(:user_logged_out, &event_handler)end++ context "with push subscriptions" do+ let(:device_a_data) do+ { endpoint: "https://push.example.com/device-a", keys: { p256dh: "key_a", auth: "auth_a" } }+ end+ let(:device_b_data) do+ { endpoint: "https://push.example.com/device-b", keys: { p256dh: "key_b", auth: "auth_b" } }+ end++ before do+ PushSubscription.create!(user: user, data: device_a_data.to_json)+ PushSubscription.create!(user: user, data: device_b_data.to_json)+ end++ it "only removes the current device push subscription on normal logout" do+ user_provider = TestProvider.new(env)+ user_provider.log_off_user(+ {},+ user_provider.cookie_jar,+ push_subscription: device_a_data.with_indifferent_access,+ )++ remaining = user.push_subscriptions.reload+ expect(remaining.size).to eq(1)+ expect(remaining.first.parsed_data["endpoint"]).to eq("https://push.example.com/device-b")+ end++ it "preserves all push subscriptions when no push subscription data is provided" do+ user_provider = TestProvider.new(env)+ user_provider.log_off_user({}, user_provider.cookie_jar)++ expect(user.push_subscriptions.reload.size).to eq(2)+ end++ it "clears all push subscriptions on strict logout" do+ SiteSetting.log_out_strict = true++ user_provider = TestProvider.new(env)+ user_provider.log_off_user({}, user_provider.cookie_jar)++ expect(user.push_subscriptions.reload.size).to eq(0)+ end+ endenddescribe "first admin user" dodiff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex 7b49a351a4a..2e891414e29 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -1064,7 +1064,7 @@ RSpec.configure do |config|superend- def log_off_user(session, cookies)+ def log_off_user(session, cookies, push_subscription: nil)# Try using the main session as `session` sometimes is a server session(cookies.try(:request).try(:session) || session).delete(:current_user_id)super