Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Adds automatic generation of a secret key for webhook subscribers

Stefan Vermaase33fc6ae0f0e
diff --git a/api/app/models/spree/webhooks/subscriber.rb b/api/app/models/spree/webhooks/subscriber.rb
index c651516154..724fda4d19 100644
--- a/api/app/models/spree/webhooks/subscriber.rb
+++ b/api/app/models/spree/webhooks/subscriber.rb
@@ -18,6 +18,7 @@ module Spree
scope :active, -> { where(active: true) }
scope :inactive, -> { where(active: false) }
+ before_validation :generate_secret_key, unless: :secret_key?
before_save :parse_subscriptions
def self.with_urls_for(event)
@@ -52,6 +53,10 @@ module Spree
errors.add(:url, 'the URL must have a path') if uri.blank? || uri.path.blank?
end
+ def generate_secret_key
+ assign_attributes(secret_key: SecureRandom.urlsafe_base64(32))
+ end
+
def parse_subscriptions
return if subscriptions.blank? || subscriptions.is_a?(Array)
diff --git a/api/spec/models/spree/webhooks/subscriber_spec.rb b/api/spec/models/spree/webhooks/subscriber_spec.rb
index fe5a6894c9..854e4c4420 100644
--- a/api/spec/models/spree/webhooks/subscriber_spec.rb
+++ b/api/spec/models/spree/webhooks/subscriber_spec.rb
@@ -19,6 +19,28 @@ describe Spree::Webhooks::Subscriber do
end
end
+ describe 'before_validation' do
+ subject(:subscriber) { build(:subscriber, secret_key: nil) }
+
+ context 'without a secret key' do
+ it 'generates a new secret key' do
+ expect { subscriber.save }.to change(subscriber, :secret_key).from(nil)
+ end
+ end
+
+ context 'with secret key' do
+ let(:assigned_secret_key) { 'some-secret-key-for-webhooks' }
+
+ before do
+ subscriber.secret_key = assigned_secret_key
+ end
+
+ it 'does not overwrite the assigned secret key' do
+ expect { subscriber.save }.not_to change(subscriber, :secret_key)
+ end
+ end
+ end
+
describe 'validations' do
context 'url format (UrlValidator)' do
it 'is invalid with an invalid url' do