Skip to content

A platform for community discussion. Free, open, simple.

FIX: Use signed checkout user references in `discourse-subscriptions` (#40058)

Arpit Jalanec3fbdb7ef38
diff --git a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/hooks_controller.rb b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/hooks_controller.rb
index 99aa06ee450..2bf2755be0f 100644
--- a/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/hooks_controller.rb
+++ b/plugins/discourse-subscriptions/app/controllers/discourse_subscriptions/hooks_controller.rb
@@ -39,24 +39,28 @@ module DiscourseSubscriptions
Rails.logger.warn("#{event[:type]} data: #{checkout_session}")
end
+ user = trusted_checkout_session_user(checkout_session)
+
+ return render_json_error "user not found" if !user
+
email = checkout_session[:customer_email]
return render_json_error "email not found" if !email
+ if !checkout_session_email_belongs_to_user?(email, user)
+ return render_json_error "user not found"
+ end
+
if checkout_session[:customer].nil?
- customer = ::Stripe::Customer.create({ email: email }, stripe_request_opts)
+ customer = ::Stripe::Customer.create({ email: user.email }, stripe_request_opts)
customer_id = customer[:id]
else
customer_id = checkout_session[:customer]
end
if SiteSetting.discourse_subscriptions_enable_verbose_logging
- Rails.logger.warn("Looking up user with email: #{email}")
+ Rails.logger.warn("Processing checkout session for user: #{user.email} (id: #{user.id})")
end
- user = ::User.find_by_username_or_email(email)
-
- return render_json_error "user not found" if !user
-
discourse_customer = Customer.create(user_id: user.id, customer_id: customer_id)
subscription = checkout_session[:subscription]
@@ -135,6 +139,22 @@ module DiscourseSubscriptions
private
+ def checkout_session_email_belongs_to_user?(email, user)
+ ::UserEmail.exists?(user_id: user.id, email: ::Email.downcase(email))
+ end
+
+ def trusted_checkout_session_user(checkout_session)
+ client_reference_id =
+ checkout_session[:client_reference_id] || checkout_session["client_reference_id"]
+
+ return if client_reference_id.blank?
+
+ ::User.find_signed(
+ client_reference_id,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ )
+ end
+
def update_status(customer_id, subscription_id, status)
discourse_subscription =
Subscription.find_by(customer_id: customer_id, external_id: subscription_id)
diff --git a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscriptions.js b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscriptions.js
index 51e0dfa9890..5403a449930 100644
--- a/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscriptions.js
+++ b/plugins/discourse-subscriptions/assets/javascripts/discourse/controllers/subscriptions.js
@@ -1,9 +1,12 @@
import Controller from "@ember/controller";
import { computed } from "@ember/object";
+import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import { i18n } from "discourse-i18n";
export default class SubscriptionsController extends Controller {
+ @service currentUser;
+
init() {
super.init(...arguments);
if (this.currentUser) {
@@ -13,33 +16,38 @@ export default class SubscriptionsController extends Controller {
}
}
- @computed("email")
+ @computed(
+ "email",
+ "currentUser.discourse_subscriptions_checkout_session_user_reference"
+ )
get pricingTable() {
- try {
- const pricingTableId =
- this.siteSettings.discourse_subscriptions_pricing_table_id;
- const publishableKey =
- this.siteSettings.discourse_subscriptions_public_key;
- const pricingTableEnabled =
- this.siteSettings.discourse_subscriptions_pricing_table_enabled;
+ const pricingTableId =
+ this.siteSettings.discourse_subscriptions_pricing_table_id;
+ const publishableKey = this.siteSettings.discourse_subscriptions_public_key;
+ const pricingTableEnabled =
+ this.siteSettings.discourse_subscriptions_pricing_table_enabled;
+ const clientReferenceId =
+ this.currentUser?.discourse_subscriptions_checkout_session_user_reference;
+
+ if (!pricingTableEnabled || !pricingTableId || !publishableKey) {
+ return i18n("discourse_subscriptions.subscribe.no_products");
+ }
- if (!pricingTableEnabled || !pricingTableId || !publishableKey) {
- throw new Error("Pricing table not configured");
+ if (this.currentUser) {
+ if (!this.email || !clientReferenceId) {
+ return "";
}
- if (this.currentUser) {
- return trustHTML(`<stripe-pricing-table
+ return trustHTML(`<stripe-pricing-table
pricing-table-id="${pricingTableId}"
publishable-key="${publishableKey}"
- customer-email="${this.email}"></stripe-pricing-table>`);
- } else {
- return trustHTML(`<stripe-pricing-table
+ customer-email="${this.email}"
+ client-reference-id="${clientReferenceId}"></stripe-pricing-table>`);
+ } else {
+ return trustHTML(`<stripe-pricing-table
pricing-table-id="${pricingTableId}"
publishable-key="${publishableKey}"
></stripe-pricing-table>`);
- }
- } catch {
- return i18n("discourse_subscriptions.subscribe.no_products");
}
}
}
diff --git a/plugins/discourse-subscriptions/plugin.rb b/plugins/discourse-subscriptions/plugin.rb
index 5dce15af784..4e604e146c4 100644
--- a/plugins/discourse-subscriptions/plugin.rb
+++ b/plugins/discourse-subscriptions/plugin.rb
@@ -60,6 +60,8 @@ end
module ::DiscourseSubscriptions
PLUGIN_NAME = "discourse-subscriptions"
+ CHECKOUT_SESSION_USER_REFERENCE_PURPOSE = "checkout_user"
+ CHECKOUT_SESSION_USER_REFERENCE_EXPIRES_IN = 30.days
end
require_relative "lib/discourse_subscriptions/engine"
@@ -77,6 +79,20 @@ after_initialize do
Discourse::Application.routes.append { mount DiscourseSubscriptions::Engine, at: "s" }
+ add_to_serializer(
+ :current_user,
+ :discourse_subscriptions_checkout_session_user_reference,
+ include_condition: -> do
+ SiteSetting.discourse_subscriptions_enabled &&
+ SiteSetting.discourse_subscriptions_pricing_table_enabled
+ end,
+ ) do
+ object.signed_id(
+ expires_in: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_EXPIRES_IN,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ )
+ end
+
add_to_serializer(:site, :show_campaign_banner) do
enabled = SiteSetting.discourse_subscriptions_enabled
campaign_enabled = SiteSetting.discourse_subscriptions_campaign_enabled
diff --git a/plugins/discourse-subscriptions/spec/requests/hooks_controller_spec.rb b/plugins/discourse-subscriptions/spec/requests/hooks_controller_spec.rb
index 33dd5e513d1..2e89ee18f19 100644
--- a/plugins/discourse-subscriptions/spec/requests/hooks_controller_spec.rb
+++ b/plugins/discourse-subscriptions/spec/requests/hooks_controller_spec.rb
@@ -36,6 +36,12 @@ RSpec.describe DiscourseSubscriptions::HooksController do
Fabricate(:subscription, external_id: "sub_12345", customer_id: customer.id, status: nil)
end
let(:group) { Fabricate(:group, name: "subscribers-group") }
+ let(:client_reference_id) do
+ user.signed_id(
+ expires_in: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_EXPIRES_IN,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ )
+ end
let(:event_data) do
{
@@ -74,6 +80,7 @@ RSpec.describe DiscourseSubscriptions::HooksController do
object: "checkout.session",
customer: customer.customer_id,
customer_email: user.email,
+ client_reference_id: client_reference_id,
invoice: "in_1P9b7iEYXaQnncSh81AQtuHD",
metadata: {
},
@@ -95,6 +102,7 @@ RSpec.describe DiscourseSubscriptions::HooksController do
object: "checkout.session",
customer: nil,
customer_email: user.email,
+ client_reference_id: client_reference_id,
invoice: nil,
metadata: {
},
@@ -190,6 +198,25 @@ RSpec.describe DiscourseSubscriptions::HooksController do
expect(response.status).to eq 200
end
+ it "accepts a secondary email that belongs to the signed user" do
+ secondary_email = "secondary-#{user.id}@example.com"
+ ::UserEmail.create!(user: user, email: secondary_email, primary: false)
+ data = checkout_session_completed_data.deep_dup
+ data[:object][:customer_email] = secondary_email
+ ::Stripe::Webhook.stubs(:construct_event).returns(
+ type: "checkout.session.completed",
+ data: data,
+ )
+
+ expect { post "/s/hooks.json" }.to change { user.reload.groups.count }.by(1)
+
+ aggregate_failures do
+ expect(response.status).to eq(200)
+ expect(group.reload.users).to contain_exactly(user)
+ expect(DiscourseSubscriptions::Customer.order(:id).last.user_id).to eq(user.id)
+ end
+ end
+
describe "completing the subscription" do
it "adds the user to the group when completing the transaction" do
expect { post "/s/hooks.json" }.to change { user.groups.count }.by(1)
@@ -209,9 +236,14 @@ RSpec.describe DiscourseSubscriptions::HooksController do
end
end
- describe "checkout.session.completed with bad data" do
+ describe "checkout.session.completed with unsigned metadata user id" do
+ fab!(:other_user, :user)
+
before do
- event = { type: "checkout.session.completed", data: checkout_session_completed_bad_data }
+ data = checkout_session_completed_data.deep_dup
+ data[:object][:metadata] = { user_id: other_user.id }
+ event = { type: "checkout.session.completed", data: data }
+
::Stripe::Checkout::Session
.stubs(:list_line_items)
.with(
@@ -221,11 +253,141 @@ RSpec.describe DiscourseSubscriptions::HooksController do
)
.returns(list_line_items_data)
+ ::Stripe::Subscription.stubs(:update).returns({})
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "ignores unsigned metadata" do
+ expect { post "/s/hooks.json" }.to change { user.reload.groups.count }.by(1)
+
+ aggregate_failures do
+ expect(response.status).to eq(200)
+ expect(group.reload.users).to contain_exactly(user)
+ expect(DiscourseSubscriptions::Customer.order(:id).last.user_id).to eq(user.id)
+ end
+ end
+ end
+
+ describe "checkout.session.completed with conflicting email" do
+ fab!(:other_user, :user)
+
+ before do
+ data = checkout_session_completed_data.deep_dup
+ data[:object][:customer_email] = other_user.email
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Subscription.expects(:update).never
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "rejects the mismatched checkout email" do
+ expect { post "/s/hooks.json" }.not_to change { DiscourseSubscriptions::Customer.count }
+
+ aggregate_failures do
+ expect(response.status).to eq(422)
+ expect(group.reload.users).to be_empty
+ end
+ end
+ end
+
+ describe "checkout.session.completed without customer and with conflicting email" do
+ fab!(:other_user, :user)
+
+ before do
+ data = checkout_session_completed_data_one_off.deep_dup
+ data[:object][:customer_email] = other_user.email
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Customer.expects(:create).never
+ ::Stripe::Subscription.expects(:update).never
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "rejects before creating a Stripe customer" do
+ expect { post "/s/hooks.json" }.not_to change { DiscourseSubscriptions::Customer.count }
+
+ aggregate_failures do
+ expect(response.status).to eq(422)
+ expect(group.reload.users).to be_empty
+ end
+ end
+ end
+
+ describe "checkout.session.completed without a trusted user reference" do
+ before do
+ data = checkout_session_completed_data.deep_dup
+ data[:object].delete(:client_reference_id)
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Subscription.expects(:update).never
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "does not bind by customer email" do
+ expect { post "/s/hooks.json" }.not_to change { DiscourseSubscriptions::Customer.count }
+
+ aggregate_failures do
+ expect(response.status).to eq(422)
+ expect(group.reload.users).to be_empty
+ end
+ end
+ end
+
+ describe "checkout.session.completed with an invalid user reference" do
+ before do
+ data = checkout_session_completed_data.deep_dup
+ data[:object][:client_reference_id] = "tampered-reference"
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Subscription.expects(:update).never
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "does not fall back to customer email" do
+ expect { post "/s/hooks.json" }.not_to change { DiscourseSubscriptions::Customer.count }
+
+ aggregate_failures do
+ expect(response.status).to eq(422)
+ expect(group.reload.users).to be_empty
+ end
+ end
+ end
+
+ describe "checkout.session.completed without customer email" do
+ before do
+ data = checkout_session_completed_data.deep_dup
+ data[:object][:customer_email] = nil
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Subscription.expects(:update).never
+ ::Stripe::Webhook.stubs(:construct_event).returns(event)
+ end
+
+ it "keeps rejecting the event" do
+ expect { post "/s/hooks.json" }.not_to change { DiscourseSubscriptions::Customer.count }
+
+ aggregate_failures do
+ expect(response.status).to eq(422)
+ expect(group.reload.users).to be_empty
+ end
+ end
+ end
+
+ describe "checkout.session.completed with bad data" do
+ before do
+ data = checkout_session_completed_bad_data.deep_dup
+ data[:object][:client_reference_id] = client_reference_id
+ event = { type: "checkout.session.completed", data: data }
+
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Customer.expects(:create).never
+ ::Stripe::Subscription.expects(:update).never
::Stripe::Webhook.stubs(:construct_event).returns(event)
- ::Stripe::Customer
- .stubs(:create)
- .with(anything, DiscourseSubscriptions::Stripe.request_opts)
- .returns(id: "cus_1234")
end
it "is returns 422" do
@@ -252,7 +414,7 @@ RSpec.describe DiscourseSubscriptions::HooksController do
::Stripe::Webhook.stubs(:construct_event).returns(event)
::Stripe::Customer
.stubs(:create)
- .with(anything, DiscourseSubscriptions::Stripe.request_opts)
+ .with({ email: user.email }, DiscourseSubscriptions::Stripe.request_opts)
.returns(id: "cus_1234")
end
@@ -264,23 +426,15 @@ RSpec.describe DiscourseSubscriptions::HooksController do
describe "checkout.session.completed with anonymous user" do
before do
- checkout_session_completed_bad_data[:object][:customer_email] = "[email protected]"
- data = checkout_session_completed_bad_data
+ data = checkout_session_completed_bad_data.deep_dup
+ data[:object][:customer_email] = "[email protected]"
+ data[:object][:client_reference_id] = client_reference_id
event = { type: "checkout.session.completed", data: data }
- ::Stripe::Checkout::Session
- .stubs(:list_line_items)
- .with(
- checkout_session_completed_data[:object][:id],
- { limit: 1 },
- DiscourseSubscriptions::Stripe.request_opts,
- )
- .returns(list_line_items_data)
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Customer.expects(:create).never
+ ::Stripe::Subscription.expects(:update).never
::Stripe::Webhook.stubs(:construct_event).returns(event)
- ::Stripe::Customer
- .stubs(:create)
- .with(anything, DiscourseSubscriptions::Stripe.request_opts)
- .returns(id: "cus_1234")
end
it "is returns 422" do
@@ -289,20 +443,16 @@ RSpec.describe DiscourseSubscriptions::HooksController do
end
end
- describe "checkout.session.completed with no customer email" do
+ describe "checkout.session.completed with no customer email or customer" do
before do
- checkout_session_completed_bad_data[:object][:customer_email] = nil
- data = checkout_session_completed_bad_data
+ data = checkout_session_completed_bad_data.deep_dup
+ data[:object][:customer_email] = nil
+ data[:object][:client_reference_id] = client_reference_id
event = { type: "checkout.session.completed", data: data }
- ::Stripe::Checkout::Session
- .stubs(:list_line_items)
- .with(
- checkout_session_completed_data[:object][:id],
- { limit: 1 },
- DiscourseSubscriptions::Stripe.request_opts,
- )
- .returns(list_line_items_data)
+ ::Stripe::Checkout::Session.expects(:list_line_items).never
+ ::Stripe::Customer.expects(:create).never
+ ::Stripe::Subscription.expects(:update).never
::Stripe::Webhook.stubs(:construct_event).returns(event)
end
diff --git a/plugins/discourse-subscriptions/spec/serializers/current_user_serializer_spec.rb b/plugins/discourse-subscriptions/spec/serializers/current_user_serializer_spec.rb
new file mode 100644
index 00000000000..fb1402242d5
--- /dev/null
+++ b/plugins/discourse-subscriptions/spec/serializers/current_user_serializer_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe CurrentUserSerializer do
+ fab!(:user)
+
+ let(:serializer) { described_class.new(user, scope: Guardian.new(user), root: false) }
+
+ before do
+ SiteSetting.discourse_subscriptions_enabled = true
+ SiteSetting.discourse_subscriptions_pricing_table_enabled = true
+ end
+
+ it "includes a signed checkout session user reference" do
+ user_reference = serializer.discourse_subscriptions_checkout_session_user_reference
+
+ expect(user_reference.length).to be <= 200
+ expect(
+ User.find_signed(
+ user_reference,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ ),
+ ).to eq(user)
+ end
+
+ it "expires the signed checkout session user reference" do
+ user_reference = serializer.discourse_subscriptions_checkout_session_user_reference
+
+ freeze_time(
+ (DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_EXPIRES_IN + 1.second).from_now,
+ ) do
+ expect(
+ User.find_signed(
+ user_reference,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ ),
+ ).to be_nil
+ end
+ end
+
+ it "omits the user reference when pricing tables are disabled" do
+ SiteSetting.discourse_subscriptions_pricing_table_enabled = false
+
+ expect(serializer.include_discourse_subscriptions_checkout_session_user_reference?).to eq(false)
+ end
+end
diff --git a/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb b/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb
index 8a542104f05..f020b2532d1 100644
--- a/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb
+++ b/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb
@@ -92,6 +92,24 @@ RSpec.describe "Pricing Table" do
)
end
+ it "Passes a signed user reference to Stripe" do
+ sign_in(admin)
+ SiteSetting.discourse_subscriptions_pricing_table_id = "prctbl_123"
+
+ visit("/s/subscriptions")
+
+ pricing_table = find("stripe-pricing-table", visible: :all)
+ client_reference_id = pricing_table["client-reference-id"]
+
+ expect(client_reference_id).to be_present
+ expect(
+ User.find_signed(
+ client_reference_id,
+ purpose: DiscourseSubscriptions::CHECKOUT_SESSION_USER_REFERENCE_PURPOSE,
+ ),
+ ).to eq(admin)
+ end
+
it "Shows a log in message if not signed in" do
visit("/")
diff --git a/plugins/discourse-subscriptions/test/javascripts/unit/controllers/subscriptions-test.js b/plugins/discourse-subscriptions/test/javascripts/unit/controllers/subscriptions-test.js
new file mode 100644
index 00000000000..4549bb759ca
--- /dev/null
+++ b/plugins/discourse-subscriptions/test/javascripts/unit/controllers/subscriptions-test.js
@@ -0,0 +1,65 @@
+import { settled } from "@ember/test-helpers";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { i18n } from "discourse-i18n";
+
+module("Unit | Controller | subscriptions", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ const siteSettings = this.owner.lookup("service:site-settings");
+ siteSettings.discourse_subscriptions_pricing_table_enabled = true;
+ siteSettings.discourse_subscriptions_pricing_table_id = "prctbl_123";
+ siteSettings.discourse_subscriptions_public_key = "pk_test_123";
+
+ this.currentUser = {
+ checkEmail() {
+ return Promise.resolve();
+ },
+ };
+ this.owner.unregister("service:current-user");
+ this.owner.register("service:current-user", this.currentUser, {
+ instantiate: false,
+ });
+ });
+
+ test("returns empty content while current user data loads", async function (assert) {
+ this.currentUser.email = "[email protected]";
+ this.currentUser.discourse_subscriptions_checkout_session_user_reference =
+ "signed-reference";
+
+ const controller = this.owner.lookup("controller:subscriptions");
+
+ assert.strictEqual(controller.pricingTable, "");
+
+ await settled();
+
+ assert.true(
+ String(controller.pricingTable).includes(
+ 'customer-email="[email protected]"'
+ )
+ );
+ });
+
+ test("returns empty content when current user reference is missing", async function (assert) {
+ this.currentUser.email = "[email protected]";
+
+ const controller = this.owner.lookup("controller:subscriptions");
+
+ await settled();
+
+ assert.strictEqual(controller.pricingTable, "");
+ });
+
+ test("returns no products when pricing table is not configured", function (assert) {
+ const siteSettings = this.owner.lookup("service:site-settings");
+ siteSettings.discourse_subscriptions_pricing_table_id = "";
+
+ const controller = this.owner.lookup("controller:subscriptions");
+
+ assert.strictEqual(
+ controller.pricingTable,
+ i18n("discourse_subscriptions.subscribe.no_products")
+ );
+ });
+});