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.

Own and handle Admin User password resets

Damian Legawieca5fb07e4057a
diff --git a/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb
new file mode 100644
index 0000000000..0bedca488a
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/password_resets_controller.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+module Spree
+ module Api
+ module V3
+ module Admin
+ class PasswordResetsController < Admin::BaseController
+ include Spree::Api::V3::Admin::AuthCookies
+
+ skip_scope_check!
+ rate_limit to: Spree::Api::Config[:rate_limit_password_reset],
+ within: Spree::Api::Config[:rate_limit_window].seconds,
+ store: Rails.cache,
+ with: RATE_LIMIT_RESPONSE
+
+ skip_before_action :authenticate_admin!
+
+ # POST /api/v3/admin/password_resets
+ def create
+ redirect_url = params[:redirect_url]
+
+ # Validate redirect_url against allowed origins (secure by default).
+ # If no allowed origins are configured, redirect_url is silently ignored
+ # to prevent open redirect / token exfiltration attacks.
+ if redirect_url.present?
+ unless current_store.allowed_origins.exists? && current_store.allowed_origin?(redirect_url)
+ redirect_url = nil
+ end
+ end
+
+ user = Spree.admin_user_class.find_by(email: params[:email])
+
+ if user
+ token = user.generate_token_for(:password_reset)
+ event_payload = { reset_token: token, email: user.email, store_id: current_store.prefixed_id }
+ event_payload[:redirect_url] = redirect_url if redirect_url.present?
+ user.publish_event('admin_user.password_reset_requested', event_payload)
+ end
+
+ # Always return 202 to prevent email enumeration
+ render json: { message: Spree.t(:password_reset_requested, scope: :api) }, status: :accepted
+ end
+
+ # PATCH /api/v3/admin/password_resets/:id
+ def update
+ user = Spree.admin_user_class.find_by_password_reset_token(params[:id])
+
+ unless user
+ return render_error(
+ code: ERROR_CODES[:password_reset_token_invalid],
+ message: Spree.t(:password_reset_token_invalid, scope: :api),
+ status: :unprocessable_content
+ )
+ end
+
+ if user.update(password: params[:password], password_confirmation: params[:password_confirmation])
+ user.publish_event('admin_user.password_reset')
+ refresh_token = Spree::RefreshToken.create_for(user, request_env: request_env_for_token)
+ set_refresh_cookie(refresh_token)
+
+ render json: auth_response(user)
+ else
+ render_errors(user.errors)
+ end
+ end
+
+ private
+
+ def auth_response(user)
+ {
+ token: generate_jwt(user, audience: JWT_AUDIENCE_ADMIN),
+ user: admin_user_serializer.new(user, params: serializer_params).to_h
+ }
+ end
+
+ def serializer_params
+ {
+ store: current_store,
+ locale: current_locale,
+ currency: current_currency,
+ user: nil,
+ includes: []
+ }
+ end
+
+ def admin_user_serializer
+ Spree.api.admin_admin_user_serializer
+ end
+
+ def request_env_for_token
+ {
+ ip_address: request.remote_ip,
+ user_agent: request.user_agent&.truncate(255)
+ }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/subscribers/spree/webhook_event_subscriber.rb b/spree/api/app/subscribers/spree/webhook_event_subscriber.rb
index 20840d248c..790e1f1493 100644
--- a/spree/api/app/subscribers/spree/webhook_event_subscriber.rb
+++ b/spree/api/app/subscribers/spree/webhook_event_subscriber.rb
@@ -17,9 +17,15 @@ module Spree
class WebhookEventSubscriber < Spree::Subscriber
subscribes_to '*'
+ # Admin auth events carry live credentials (password reset tokens) and have
+ # no legitimate external consumer — core delivers those emails itself.
+ # Never forward them to webhook endpoints, including '*' subscriptions.
+ NON_DELIVERABLE_EVENTS = %w[admin_user.password_reset_requested].freeze
+
def handle(event)
return unless Spree::Api::Config.webhooks_enabled
return if event.store_id.blank?
+ return if NON_DELIVERABLE_EVENTS.include?(event.name)
# Only load the columns we need for matching and delivery
endpoints = Spree::WebhookEndpoint
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 861771f1b4..5a7b9bf353 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -134,6 +134,12 @@ Spree::Core::Engine.add_routes do
get 'auth/invitations/:id/lookup', to: 'invitation_acceptances#lookup'
post 'auth/invitations/:id/accept', to: 'invitation_acceptances#accept'
+ # Public password reset — unauthenticated; the token is the credential.
+ # Mounted under `auth/` so the refresh-token cookie issued on success
+ # shares its path with `/auth/refresh`.
+ post 'auth/password_resets', to: 'password_resets#create'
+ patch 'auth/password_resets/:id', to: 'password_resets#update'
+
# Dashboard
namespace :dashboard do
get :analytics
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/password_resets_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/password_resets_controller_spec.rb
new file mode 100644
index 0000000000..20f296976e
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/password_resets_controller_spec.rb
@@ -0,0 +1,65 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::PasswordResetsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin'
+
+ let!(:admin_user) { create(:admin_user, email: '[email protected]') }
+
+ describe 'POST #create' do
+ before do
+ allow(Spree::Events).to receive(:enabled?).and_return(true)
+ end
+ it 'publishes the password reset event and returns 202' do
+ allow(Spree::Events).to receive(:publish)
+
+ post :create, params: { email: '[email protected]' }
+
+ expect(response).to have_http_status(:accepted)
+ expect(Spree::Events).to have_received(:publish).with(
+ 'admin_user.password_reset_requested',
+ hash_including(reset_token: an_instance_of(String), email: '[email protected]', store_id: store.prefixed_id),
+ anything
+ )
+ end
+
+ it 'returns 202 for unknown emails without publishing (no enumeration)' do
+ allow(Spree::Events).to receive(:publish)
+
+ post :create, params: { email: '[email protected]' }
+
+ expect(response).to have_http_status(:accepted)
+ expect(Spree::Events).not_to have_received(:publish)
+ end
+
+ it 'ignores redirect_url when no allowed origins are configured' do
+ allow(Spree::Events).to receive(:publish)
+
+ post :create, params: { email: '[email protected]', redirect_url: 'https://evil.example.com' }
+
+ expect(Spree::Events).to have_received(:publish) do |_name, payload, _meta|
+ expect(payload).not_to have_key(:redirect_url)
+ end
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'sets the new password and returns a JWT with the admin user' do
+ token = admin_user.generate_token_for(:password_reset)
+
+ patch :update, params: { id: token, password: 'new-secret-123', password_confirmation: 'new-secret-123' }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['token']).to be_present
+ expect(json_response['user']['id']).to eq(admin_user.prefixed_id)
+ expect(admin_user.reload.valid_password?('new-secret-123')).to be(true)
+ end
+
+ it 'rejects an invalid token' do
+ patch :update, params: { id: 'bogus', password: 'new-secret-123', password_confirmation: 'new-secret-123' }
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+end
diff --git a/spree/api/spec/subscribers/spree/webhook_event_subscriber_spec.rb b/spree/api/spec/subscribers/spree/webhook_event_subscriber_spec.rb
index 30d35bcf22..0ab02df053 100644
--- a/spree/api/spec/subscribers/spree/webhook_event_subscriber_spec.rb
+++ b/spree/api/spec/subscribers/spree/webhook_event_subscriber_spec.rb
@@ -18,6 +18,18 @@ module Spree
end
describe '#handle' do
+ context 'with a non-deliverable auth event' do
+ let!(:webhook_endpoint) { create(:webhook_endpoint, store: store, subscriptions: ['*']) }
+ let(:event_name) { 'admin_user.password_reset_requested' }
+ let(:event_payload) { { reset_token: 'secret', email: '[email protected]' } }
+
+ it 'never delivers admin credentials, even to wildcard subscriptions' do
+ expect {
+ described_class.new.handle(event)
+ }.not_to change(Spree::WebhookDelivery, :count)
+ end
+ end
+
context 'when webhooks are enabled' do
it 'creates a webhook delivery record' do
expect {
diff --git a/spree/core/app/mailers/spree/admin_user_mailer.rb b/spree/core/app/mailers/spree/admin_user_mailer.rb
new file mode 100644
index 0000000000..fe78bb9d19
--- /dev/null
+++ b/spree/core/app/mailers/spree/admin_user_mailer.rb
@@ -0,0 +1,61 @@
+module Spree
+ # Auth emails for admin users. Reached two ways: the legacy Rails admin's
+ # Devise flow (via Spree::AdminUserMethods::DeviseNotifications) and the Admin
+ # API's `admin_user.password_reset_requested` event (dashboard SPA).
+ class AdminUserMailer < BaseMailer
+ def password_reset_email(admin_user, token, store, redirect_url: nil)
+ @user = admin_user
+ @current_store = store
+ @reset_url = password_reset_url(token, store, redirect_url)
+
+ with_store_locale(store) do
+ mail(
+ to: admin_user.email,
+ from: from_address,
+ reply_to: reply_to_address,
+ subject: "#{store.name} #{Spree.t('admin_user_mailer.password_reset_email.subject')}",
+ store_url: store.formatted_url
+ )
+ end
+ end
+
+ def confirmation_email(admin_user, token, store)
+ @user = admin_user
+ @current_store = store
+ @confirmation_url = confirmation_url(token, store)
+
+ with_store_locale(store) do
+ mail(
+ to: admin_user.email,
+ from: from_address,
+ reply_to: reply_to_address,
+ subject: "#{store.name} #{Spree.t('admin_user_mailer.confirmation_email.subject')}",
+ store_url: store.formatted_url
+ )
+ end
+ end
+
+ private
+
+ # The dashboard SPA passes a validated redirect URL (token appended as a
+ # query param); the legacy Devise flow links to its own edit-password route
+ # when the host app installed it.
+ def password_reset_url(token, store, redirect_url)
+ return append_token(redirect_url, token) if redirect_url.present?
+
+ if spree.respond_to?(:edit_admin_user_password_url)
+ spree.edit_admin_user_password_url(reset_password_token: token, host: store.formatted_url)
+ else
+ append_token(store.formatted_url, token)
+ end
+ end
+
+ def confirmation_url(token, store)
+ if spree.respond_to?(:admin_user_confirmation_url)
+ spree.admin_user_confirmation_url(confirmation_token: token, host: store.formatted_url)
+ else
+ append_token(store.formatted_url, token)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/admin_user_methods.rb b/spree/core/app/models/concerns/spree/admin_user_methods.rb
index f9f40732b6..43e3d1eb70 100644
--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb
+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb
@@ -7,12 +7,31 @@ module Spree
include Spree::RansackableAttributes
included do
+ # Wins over Devise's implementation regardless of module include order, so
+ # host apps that add `devise ...` after this concern still send admin auth
+ # emails through Spree's mailer.
+ prepend Spree::AdminUserMethods::DeviseNotifications
+
has_prefix_id :admin
has_person_name
normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }
+ # Token auto-invalidates when password changes (salt changes)
+ # Expiration is configurable via Spree::Config.admin_password_reset_expires_in (in minutes)
+ generates_token_for :password_reset, expires_in: Spree::Config.admin_password_reset_expires_in.minutes do
+ password_salt&.last(10) || encrypted_password&.last(10)
+ end
+
+ def self.find_by_password_reset_token(token)
+ find_by_token_for(:password_reset, token)
+ end
+
+ def self.find_by_password_reset_token!(token)
+ find_by_token_for!(:password_reset, token)
+ end
+
# Associations
has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
has_many :canceled_orders, class_name: 'Spree::Order', foreign_key: :canceler_id
@@ -80,5 +99,25 @@ module Spree
reports.destroy_all
exports.destroy_all
end
+
+ # Routes Devise's auth notifications through Spree's own mailer so admin
+ # password reset and account confirmation emails carry the store design and
+ # locale instead of Devise's built-in templates. Other notification kinds
+ # (e.g. unlock instructions) fall through to Devise.
+ module DeviseNotifications
+ def send_devise_notification(notification, *args)
+ token = args.first
+ store = Spree::Current.store || Spree::Store.default
+
+ case notification
+ when :reset_password_instructions
+ Spree::AdminUserMailer.password_reset_email(self, token, store).deliver_later
+ when :confirmation_instructions
+ Spree::AdminUserMailer.confirmation_email(self, token, store).deliver_later
+ else
+ super
+ end
+ end
+ end
end
end
diff --git a/spree/core/app/subscribers/spree/admin_user_email_subscriber.rb b/spree/core/app/subscribers/spree/admin_user_email_subscriber.rb
new file mode 100644
index 0000000000..722bbc29dd
--- /dev/null
+++ b/spree/core/app/subscribers/spree/admin_user_email_subscriber.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module Spree
+ class AdminUserEmailSubscriber < Spree::Subscriber
+ subscribes_to 'admin_user.password_reset_requested'
+
+ def handle(event)
+ user = Spree.admin_user_class.find_by(email: event.payload['email'])
+ return unless user
+
+ store = find_store(event)
+
+ AdminUserMailer.password_reset_email(
+ user,
+ event.payload['reset_token'],
+ store,
+ redirect_url: event.payload['redirect_url']
+ ).deliver_later
+ end
+
+ private
+
+ def find_store(event)
+ Spree::Store.find_by_prefix_id(event.payload['store_id']) ||
+ Spree::Current.store ||
+ Spree::Store.default
+ end
+ end
+end
diff --git a/spree/core/app/views/spree/admin_user_mailer/confirmation_email.html.erb b/spree/core/app/views/spree/admin_user_mailer/confirmation_email.html.erb
new file mode 100644
index 0000000000..6d06fe358f
--- /dev/null
+++ b/spree/core/app/views/spree/admin_user_mailer/confirmation_email.html.erb
@@ -0,0 +1,7 @@
+<%= render layout: 'spree/shared/mailer_hero' do %>
+ <h1><%= Spree.t('admin_user_mailer.confirmation_email.action') %></h1>
+ <p class="greeting"><%= Spree.t('admin_user_mailer.confirmation_email.greeting', name: @user.first_name.presence || @user.email) %></p>
+ <p><%= Spree.t('admin_user_mailer.confirmation_email.instructions', store_name: @current_store.name) %></p>
+ <%= render 'spree/shared/mailer_button', url: @confirmation_url, label: Spree.t('admin_user_mailer.confirmation_email.action') %>
+ <p class="sub"><%= Spree.t('admin_user_mailer.confirmation_email.ignore_notice') %></p>
+<% end %>
diff --git a/spree/core/app/views/spree/admin_user_mailer/password_reset_email.html.erb b/spree/core/app/views/spree/admin_user_mailer/password_reset_email.html.erb
new file mode 100644
index 0000000000..94959395b4
--- /dev/null
+++ b/spree/core/app/views/spree/admin_user_mailer/password_reset_email.html.erb
@@ -0,0 +1,8 @@
+<%= render layout: 'spree/shared/mailer_hero' do %>
+ <h1><%= Spree.t('admin_user_mailer.password_reset_email.action') %></h1>
+ <p class="greeting"><%= Spree.t('admin_user_mailer.password_reset_email.greeting', name: @user.first_name.presence || @user.email) %></p>
+ <p><%= Spree.t('admin_user_mailer.password_reset_email.instructions', store_name: @current_store.name) %></p>
+ <%= render 'spree/shared/mailer_button', url: @reset_url, label: Spree.t('admin_user_mailer.password_reset_email.action') %>
+ <p class="sub"><%= Spree.t('admin_user_mailer.password_reset_email.expiry_notice') %></p>
+ <p class="sub"><%= Spree.t('admin_user_mailer.password_reset_email.ignore_notice') %></p>
+<% end %>
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 193ca227e5..692091452c 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -666,6 +666,20 @@ en:
adjustments: Adjustments
adjustments_deleted: Adjustments Deleted
admin_locale: Admin locale
+ admin_user_mailer:
+ confirmation_email:
+ action: Confirm Email
+ greeting: Hi %{name},
+ ignore_notice: If you did not create this account, you can safely ignore this email.
+ instructions: Please confirm the email address for your %{store_name} admin account by clicking the button below.
+ subject: Email Confirmation Instructions
+ password_reset_email:
+ action: Reset Password
+ expiry_notice: This password reset link will expire shortly. If you did not request this, no action is needed.
+ greeting: Hi %{name},
+ ignore_notice: If you did not request a password reset, you can safely ignore this email. Your password will not be changed.
+ instructions: We received a request to reset the password for your %{store_name} admin account. Click the button below to choose a new password.
+ subject: Password Reset Instructions
administration: Administration
advertise: Advertise
all: All
diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index c8fe2847ff..61d7f66010 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -118,6 +118,7 @@ module Spree
preference :coupon_codes_total_limit, :integer, default: 5000 # the maximum number of coupon codes to be generated
# password reset
+ preference :admin_password_reset_expires_in, :integer, default: 15 # admin password reset token expiration time in minutes
preference :customer_password_reset_expires_in, :integer, default: 15 # password reset token expiration time in minutes
# gift cards
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 7659288fef..33ecdf9cd9 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -356,6 +356,7 @@ module Spree
Spree::ExportSubscriber,
Spree::ReportSubscriber,
Spree::InvitationEmailSubscriber,
+ Spree::AdminUserEmailSubscriber,
Spree::ProductMetricsSubscriber
]
diff --git a/spree/core/lib/spree/core/previews/admin_user_preview.rb b/spree/core/lib/spree/core/previews/admin_user_preview.rb
new file mode 100644
index 0000000000..1a98ee2834
--- /dev/null
+++ b/spree/core/lib/spree/core/previews/admin_user_preview.rb
@@ -0,0 +1,22 @@
+require_relative 'preview_data'
+
+# Preview Spree admin user auth emails at /rails/mailers/spree/admin_user
+class Spree::AdminUserPreview < ActionMailer::Preview
+ include Spree::PreviewData::LocaleParam
+
+ def password_reset_email
+ Spree::AdminUserMailer.password_reset_email(
+ Spree::PreviewData.admin_user,
+ 'preview-token',
+ Spree::PreviewData.store(locale)
+ )
+ end
+
+ def confirmation_email
+ Spree::AdminUserMailer.confirmation_email(
+ Spree::PreviewData.admin_user,
+ 'preview-token',
+ Spree::PreviewData.store(locale)
+ )
+ end
+end
diff --git a/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb b/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb
new file mode 100644
index 0000000000..cf2b00a1f7
--- /dev/null
+++ b/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+describe Spree::AdminUserMailer, type: :mailer do
+ let(:store) { @default_store }
+ let(:admin_user) { create(:admin_user, email: '[email protected]') }
+ let(:token) { 'secret-reset-token' }
+
+ describe '#password_reset_email' do
+ it 'sends to the admin with the store-prefixed subject' do
+ message = described_class.password_reset_email(admin_user, token, store)
+
+ expect(message.to).to eq(['[email protected]'])
+ expect(message.subject).to eq("#{store.name} #{Spree.t('admin_user_mailer.password_reset_email.subject')}")
+ end
+
+ it 'links with the reset token' do
+ message = described_class.password_reset_email(admin_user, token, store)
+
+ expect(message.body.encoded).to include("token=#{token}")
+ end
+
+ it 'prefers the redirect URL when the API validated one (dashboard SPA)' do
+ message = described_class.password_reset_email(admin_user, token, store, redirect_url: 'https://admin.example.com/reset-password')
+
+ expect(message.body.encoded).to include("https://admin.example.com/reset-password?token=#{token}")
+ end
+ end
+
+ describe '#confirmation_email' do
+ it 'sends the confirmation with the store-prefixed subject and token link' do
+ message = described_class.confirmation_email(admin_user, token, store)
+
+ expect(message.to).to eq(['[email protected]'])
+ expect(message.subject).to eq("#{store.name} #{Spree.t('admin_user_mailer.confirmation_email.subject')}")
+ expect(message.body.encoded).to include("token=#{token}")
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/admin_user_spec.rb b/spree/core/spec/models/spree/admin_user_spec.rb
index 727c905105..aabe55f4e2 100644
--- a/spree/core/spec/models/spree/admin_user_spec.rb
+++ b/spree/core/spec/models/spree/admin_user_spec.rb
@@ -3,6 +3,37 @@ require 'spec_helper'
describe Spree.admin_user_class, type: :model do
let(:admin_user) { create(:admin_user) }
+ describe 'password reset tokens' do
+ it 'round-trips through find_by_password_reset_token' do
+ token = admin_user.generate_token_for(:password_reset)
+ expect(described_class.find_by_password_reset_token(token)).to eq(admin_user)
+ end
+
+ it 'invalidates the token when the password changes' do
+ token = admin_user.generate_token_for(:password_reset)
+ admin_user.update!(password: 'new-secret-123', password_confirmation: 'new-secret-123')
+ expect(described_class.find_by_password_reset_token(token)).to be_nil
+ end
+ end
+
+ describe '#send_devise_notification (Devise bridge)' do
+ let(:mail) { double(deliver_later: true) }
+
+ it 'routes reset password instructions through Spree::AdminUserMailer' do
+ expect(Spree::AdminUserMailer).to receive(:password_reset_email).
+ with(admin_user, 'devise-token', Spree::Store.default).and_return(mail)
+
+ admin_user.send_devise_notification(:reset_password_instructions, 'devise-token', {})
+ end
+
+ it 'routes confirmation instructions through Spree::AdminUserMailer' do
+ expect(Spree::AdminUserMailer).to receive(:confirmation_email).
+ with(admin_user, 'devise-token', Spree::Store.default).and_return(mail)
+
+ admin_user.send_devise_notification(:confirmation_instructions, 'devise-token', {})
+ end
+ end
+
describe '#can_be_deleted?' do
subject { admin_user.can_be_deleted? }
diff --git a/spree/core/spec/subscribers/spree/admin_user_email_subscriber_spec.rb b/spree/core/spec/subscribers/spree/admin_user_email_subscriber_spec.rb
new file mode 100644
index 0000000000..9185ddd380
--- /dev/null
+++ b/spree/core/spec/subscribers/spree/admin_user_email_subscriber_spec.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe Spree::AdminUserEmailSubscriber do
+ let(:store) { @default_store }
+ let(:admin_user) { create(:admin_user, email: '[email protected]') }
+ let(:subscriber) { described_class.new }
+
+ def mock_event(email:, redirect_url: nil, store_id: store.prefixed_id)
+ payload = { 'email' => email, 'reset_token' => 'secret-reset-token', 'store_id' => store_id }
+ payload['redirect_url'] = redirect_url if redirect_url
+ double('Event', payload: payload)
+ end
+
+ describe 'admin_user.password_reset_requested event' do
+ it 'sends the password reset email' do
+ expect(Spree::AdminUserMailer).to receive(:password_reset_email).
+ with(admin_user, 'secret-reset-token', store, redirect_url: nil).
+ and_return(double(deliver_later: true))
+
+ subscriber.handle(mock_event(email: admin_user.email))
+ end
+
+ it 'forwards the redirect URL from the event payload' do
+ expect(Spree::AdminUserMailer).to receive(:password_reset_email).
+ with(admin_user, 'secret-reset-token', store, redirect_url: 'https://admin.example.com/reset').
+ and_return(double(deliver_later: true))
+
+ subscriber.handle(mock_event(email: admin_user.email, redirect_url: 'https://admin.example.com/reset'))
+ end
+
+ it 'does nothing when no admin user matches the email' do
+ expect(Spree::AdminUserMailer).not_to receive(:password_reset_email)
+
+ subscriber.handle(mock_event(email: '[email protected]'))
+ end
+ end
+end