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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Address platform-auth review: finish customer rename + harden migration and lockout
Łukasz Adamczyk7a55ebf35b25
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.mdindex 214e25b11f..bba787389a 100644--- a/docs/plans/6.0-platform-auth.md+++ b/docs/plans/6.0-platform-auth.md@@ -335,17 +335,21 @@ registered in the `5_6_to_6_0` upgrade manifest) copies the legacy customer tabl`spree_users`, `SOURCE_USER_TABLE`-overridable) into `spree_customers` **preserving primary keys** sothe already-renamed `customer_id` FKs still resolve, mapping `encrypted_password` → `password_digest`.Because the target is a fresh table, it copies with explicit ids and then resets the Postgres-sequence. It re-points every polymorphic `user_type` that named the old customer class+sequence. It re-points every polymorphic reference that named the old customer class(`Spree::User` → `Spree.customer_class`) on `spree_role_users`, `spree_refresh_tokens`,-`spree_user_identities`, and `spree_api_keys` (`created_by_type` + `revoked_by_type`); admin rows+`spree_user_identities`, `spree_api_keys` (`created_by_type` + `revoked_by_type`), and+`spree_customer_group_users` (whose type column was renamed `user_type` → `customer_type`); admin rows(`Spree::AdminUser`) are untouched since that class name is unchanged. Admins are handled in place —`spree_admin_users` keeps its table and class, so the task just backfills `password_digest` from thelegacy `encrypted_password`. It reads the legacy table by **table name only** (never `LegacyUser`,which is gone once all phases ship). **Passwords survive with zero resets** as long as no Devise-pepper is configured (spree-starter default); the task **aborts loudly** if `Devise.pepper` is set,-and prints a caution if Devise isn't loaded (can't verify). Blank-email rows are skipped and logged;-the source table is left in place as a safety net (a later cleanup drops it). Idempotent — re-running-skips ids already in `spree_customers`.+pepper is configured (spree-starter default); the task **aborts loudly** if `Devise.pepper` is set, and+— since Devise is gone in 6.0 and a former pepper can't be introspected — also aborts when Devise is+absent until the operator confirms none was used (`CONFIRM_NO_PEPPER=true`). A preflight aborts with the+offending ids when a source row has a blank email or an email already owned by a different customer+(`SKIP_INVALID_ROWS=true` skips them instead) — otherwise the renamed `customer_id` FKs could point at a+customer that never migrated. The source table is left in place as a safety net (a later cleanup drops+it). Idempotent — re-running skips ids already in `spree_customers`.**Path B — keep a custom user model (documented recipe, no gem code).** No data migration and no newconcern: point `Spree.customer_class` at the existing model, replace the old three-concern include setdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex dc7b688657..4615283fe7 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -428,12 +428,17 @@ admins never move — the task only backfills `password_digest` from the legacyinsert explicit ids, so it also **resets the Postgres sequence** afterward(`reset_pk_sequence!`, guarded to PG) — no prior precedent because taxon→categorypreserved ids via `rename_table`. With ids preserved, the only polymorphic fixups-are **`user_type` string re-points** `Spree::User` → `Spree.customer_class` on-`spree_role_users`, `spree_refresh_tokens`, `spree_user_identities`, and-`spree_api_keys` (`created_by_type` + `revoked_by_type`); admin-typed rows stay.-The task reads the legacy table **by name only** (never `LegacyUser`, deleted once-all phases ship together), aborts on `Devise.pepper`, skips blank-email rows, and-leaves `spree_users` in place as a safety net.+are **type-string re-points** `Spree::User` → `Spree.customer_class` on+`spree_role_users`, `spree_refresh_tokens`, `spree_user_identities`,+`spree_api_keys` (`created_by_type` + `revoked_by_type`), and+`spree_customer_group_users` (whose type column renamed `user_type` →+`customer_type` with the 2026-03-16 FK rename — **must** be re-pointed too or+memberships dangle); admin-typed rows stay. The task reads the legacy table **by+name only** (never `LegacyUser`, deleted once all phases ship together), aborts on+`Devise.pepper` (and, since Devise is gone in 6.0 and a pepper can't be+introspected, aborts when Devise is absent unless `CONFIRM_NO_PEPPER=true`),+preflight-aborts on blank-email or email-conflict rows (`SKIP_INVALID_ROWS=true`+to skip), and leaves `spree_users` in place as a safety net.**Single clash-aware create migration.** The two Phase-1 create migrations mergedinto `20260728000000_create_spree_customers_and_admin_users` — a **non-colliding**diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rbindex 64fb1e6e43..2c4fd5e448 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders_controller.rb@@ -133,7 +133,9 @@ module Spreecustomer_param = params[:customer_id].presence || params[:user_id].presencereturn unless customer_param- Spree.customer_class.find_by_param!(customer_param)+ Spree.customer_class.+ accessible_by(current_ability, :show).+ find_by_prefix_id!(customer_param)enddef order_create_paramsdiff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rbindex 2ad26d598b..e1274fce5a 100644--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb@@ -69,12 +69,12 @@ module Spree)end- linked_user = subscriber.user+ linked_customer = subscriber.customersubscriber.destroy!# Keep accepts_email_marketing in sync, but only when no subscriptions remain.- if linked_user&.accepts_email_marketing? && Spree::NewsletterSubscriber.where(user_id: linked_user.id).none?- linked_user.update(accepts_email_marketing: false)+ if linked_customer&.accepts_email_marketing? && Spree::NewsletterSubscriber.where(customer_id: linked_customer.id).none?+ linked_customer.update(accepts_email_marketing: false)endhead :no_content@@ -92,7 +92,7 @@ module Spreeemail: subscriber.email,unsubscribe_token: subscriber.generate_token_for(:unsubscribe),store_id: current_store.prefixed_id,- customer_id: subscriber.user&.prefixed_id+ customer_id: subscriber.customer&.prefixed_id}redirect_url = validated_redirect_urldiff --git a/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rbindex 122809ce94..18486cd508 100644--- a/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb@@ -29,8 +29,7 @@ module Spree# Customer the card was issued to. Gated behind `expand?` to keep# the list payload thin — the SPA's list view passes# `expand=customer,created_by` to populate the row chips.- one :user,- key: :customer,+ one :customer,resource: proc { Spree.api.admin_customer_serializer },if: proc { expand?('customer') }diff --git a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rbindex 7b9856a333..a0f2d22b87 100644--- a/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/order_serializer.rb@@ -85,8 +85,7 @@ module Spreemany :payment_methods, resource: proc { Spree.api.admin_payment_method_serializer }, if: proc { expand?('payment_methods') }- one :user,- key: :customer,+ one :customer,resource: proc { Spree.api.admin_customer_serializer },if: proc { expand?('customer') }diff --git a/spree/core/app/models/concerns/spree/account_lockout.rb b/spree/core/app/models/concerns/spree/account_lockout.rbindex 454bbaf6b2..9298b700a0 100644--- a/spree/core/app/models/concerns/spree/account_lockout.rb+++ b/spree/core/app/models/concerns/spree/account_lockout.rb@@ -17,17 +17,22 @@ module Spreeend# Records a failed login attempt, locking the account once the configured- # threshold is reached.+ # threshold is reached. Serialized with a row lock so concurrent failures+ # read the latest counter — otherwise a stale in-memory value could cross the+ # threshold without ever persisting +locked_at+.# @return [void]def record_failed_attempt!- increment!(:failed_attempts)- update!(locked_at: Time.current) if failed_attempts >= Spree::Config[:max_failed_login_attempts]+ with_lock do+ increment(:failed_attempts)+ self.locked_at = Time.current if failed_attempts >= Spree::Config[:max_failed_login_attempts]+ save!+ endend# Clears the failed-attempt counter and any lockout. Call on successful login.# @return [void]def reset_failed_attempts!- update!(failed_attempts: 0, locked_at: nil)+ with_lock { update!(failed_attempts: 0, locked_at: nil) }endendenddiff --git a/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb b/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rbindex 25dbdb51b9..90b30ae93a 100644--- a/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb+++ b/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb@@ -14,7 +14,12 @@ module Spreereturn failure('Account temporarily locked. Try again later.') if user.respond_to?(:locked?) && user.locked?if validate_password(user, password)- user.reset_failed_attempts! if user.respond_to?(:reset_failed_attempts!) && user.failed_attempts.to_i.positive?+ # Require the full lockout contract before touching the counter — a+ # custom customer_class may implement one hook but not the other.+ if user.respond_to?(:failed_attempts) && user.respond_to?(:reset_failed_attempts!) &&+ user.failed_attempts.to_i.positive?+ user.reset_failed_attempts!+ endsuccess(user)elseuser.record_failed_attempt! if user.respond_to?(:record_failed_attempt!)diff --git a/spree/core/app/models/spree/credit_card.rb b/spree/core/app/models/spree/credit_card.rbindex d5faa91188..b670e07fcb 100644--- a/spree/core/app/models/spree/credit_card.rb+++ b/spree/core/app/models/spree/credit_card.rb@@ -188,7 +188,7 @@ module Spree# match must go through #by_fingerprint's decimal cast rather than a plain# equality (which Postgres rejects as `character varying = integer`).def fingerprint_not_duplicated- duplicates = self.class.where(user_id: user_id, payment_method_id: payment_method_id).+ duplicates = self.class.where(customer_id: customer_id, payment_method_id: payment_method_id).by_fingerprint(fingerprint, month, year)duplicates = duplicates.where.not(id: id) if persisted?@@ -200,8 +200,8 @@ module Spreeenddef ensure_one_default- if user_id && default- CreditCard.where(default: true, user_id: user_id).where.not(id: id).+ if customer_id && default+ CreditCard.where(default: true, customer_id: customer_id).where.not(id: id).update_all(default: false)endenddiff --git a/spree/core/app/models/spree/gateway_customer.rb b/spree/core/app/models/spree/gateway_customer.rbindex b749b81286..964f5a427a 100644--- a/spree/core/app/models/spree/gateway_customer.rb+++ b/spree/core/app/models/spree/gateway_customer.rb@@ -9,7 +9,7 @@ module Spreevalidates :payment_method, presence: truevalidates :customer, presence: truevalidates :profile_id, presence: true- validates :payment_method_id, uniqueness: { scope: :user_id }+ validates :payment_method_id, uniqueness: { scope: :customer_id }encrypts :profile_id, deterministic: true if Rails.configuration.active_record.encryption.include?(:primary_key)enddiff --git a/spree/core/app/models/spree/order/address_book.rb b/spree/core/app/models/spree/order/address_book.rbindex 3fb0aee7df..fd9bd1d089 100644--- a/spree/core/app/models/spree/order/address_book.rb+++ b/spree/core/app/models/spree/order/address_book.rb@@ -60,7 +60,7 @@ module Spreeattributes.transform_values!(&:presence)attributes = attributes.to_h.symbolize_keys- default_address_scope = customer ? customer.addresses : ::Spree::Address.where(user_id: nil)+ default_address_scope = customer ? customer.addresses : ::Spree::Address.where(customer_id: nil)default_address = default_address_scope.find_by(id: attributes[:id])if default_address&.editable?diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rbindex 0e8133b9f2..d870ae9295 100644--- a/spree/core/app/models/spree/promotion/rules/user.rb+++ b/spree/core/app/models/spree/promotion/rules/user.rb@@ -10,8 +10,8 @@ module Spreedependent: :destroyhas_many :users, through: :promotion_rule_users, source: :customer, class_name: "::#{Spree.customer_class}"- # Customers, not admin users — the rule keys off `Spree::Order#user_id`.- # The data layer keeps the `users` association (legacy column name);+ # Customers, not admin users — the rule keys off `Spree::Order#customer_id`.+ # The data layer keeps the `users` association name (deferred model rename);# the API exposes the same set as `customer_ids`.def self.additional_permitted_attributes[customer_ids: []]@@ -50,7 +50,7 @@ module Spreeenddef eligible?(order, _options = {})- eligible_user_ids.include?(order.user_id)+ eligible_user_ids.include?(order.customer_id)enddef user_ids_string@@ -78,7 +78,7 @@ module Spreeif user_ids_to_add.any?Spree::PromotionRuleUser.insert_all(- user_ids_to_add.map { |user_id| { user_id: user_id, promotion_rule_id: id } }+ user_ids_to_add.map { |customer_id| { customer_id: customer_id, promotion_rule_id: id } })enddiff --git a/spree/core/app/models/spree/reimbursement_type/reimbursement_helpers.rb b/spree/core/app/models/spree/reimbursement_type/reimbursement_helpers.rbindex ee51813468..b8df070863 100644--- a/spree/core/app/models/spree/reimbursement_type/reimbursement_helpers.rb+++ b/spree/core/app/models/spree/reimbursement_type/reimbursement_helpers.rb@@ -46,7 +46,7 @@ module Spreedef store_credit_params(category, reimbursement, unpaid_amount){- user: reimbursement.order.customer,+ customer: reimbursement.order.customer,amount: unpaid_amount,category: category,created_by: reimbursement.order.store.users.first,diff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rbindex d8fe4cc007..bcddf952f0 100644--- a/spree/core/app/models/spree/store_credit.rb+++ b/spree/core/app/models/spree/store_credit.rb@@ -209,7 +209,7 @@ module Spreedef create_credit_record_params(amount){amount: amount,- user_id: customer_id,+ customer_id: customer_id,category_id: category_id,created_by_id: created_by_id,currency: currency,diff --git a/spree/core/app/models/spree/wishlist.rb b/spree/core/app/models/spree/wishlist.rbindex b158302d2b..da8750eabe 100644--- a/spree/core/app/models/spree/wishlist.rb+++ b/spree/core/app/models/spree/wishlist.rb@@ -22,7 +22,7 @@ module Spreehas_many :products, -> { distinct }, through: :variants, source: :product, class_name: 'Spree::Product'after_commit :ensure_default_exists_and_is_unique- validates :name, :store, :user, presence: true+ validates :name, :store, :customer, presence: truedef include?(variant_id)wished_items.exists?(variant_id: variant_id)@@ -46,7 +46,7 @@ module Spreedef ensure_default_exists_and_is_uniqueif is_default?- Wishlist.where(is_default: true, user_id: user_id, store_id: store_id).where.not(id: id).update_all(is_default: false)+ Wishlist.where(is_default: true, customer_id: customer_id, store_id: store_id).where.not(id: id).update_all(is_default: false)endendenddiff --git a/spree/core/app/services/spree/gift_cards/apply.rb b/spree/core/app/services/spree/gift_cards/apply.rbindex 1faea50074..0fb540f65e 100644--- a/spree/core/app/services/spree/gift_cards/apply.rb+++ b/spree/core/app/services/spree/gift_cards/apply.rb@@ -37,7 +37,7 @@ module Spreestore_credit = gift_card.store_credits.create!(store: store,- user: order.customer,+ customer: order.customer,amount: amount,currency: order.currency,originator: gift_card,diff --git a/spree/core/db/migrate/20260728000000_create_spree_customers_and_admin_users.rb b/spree/core/db/migrate/20260728000000_create_spree_customers_and_admin_users.rbindex 5ddf8e81d6..570455f8c1 100644--- a/spree/core/db/migrate/20260728000000_create_spree_customers_and_admin_users.rb+++ b/spree/core/db/migrate/20260728000000_create_spree_customers_and_admin_users.rb@@ -33,7 +33,7 @@ class CreateSpreeCustomersAndAdminUsers < ActiveRecord::Migration[7.2]t.string :last_namet.string :phonet.string :selected_locale- t.boolean :accepts_email_marketing+ t.boolean :accepts_email_marketing, null: falset.bigint :bill_address_idt.bigint :ship_address_idt.integer :failed_attemptsdiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlindex e5f8ef44e8..14c525d9b3 100644--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -60,15 +60,22 @@ steps:Copies the legacy Devise user table (default spree_users) intospree_customers, preserving ids so the renamed customer_id foreign keysstill resolve and mapping encrypted_password -> password_digest, then- re-points every polymorphic user_type that named the old customer class- (default Spree::User) to Spree::Customer and backfills password_digest on- spree_admin_users.+ re-points every polymorphic reference that named the old customer class+ (default Spree::User) to Spree::Customer — the user_type columns plus+ customer_type on customer-group memberships — and backfills password_digest+ on spree_admin_users.Precondition: NO Devise pepper. encrypted_password is a plain bcrypt digestthat has_secure_password reads directly only when unpeppered; the task- aborts if Devise.pepper is set. Peppered / SSO / non-bcrypt installs keep a- custom customer_class instead (see the 5.6-to-6.0 upgrade guide) and skip- this step.+ aborts if Devise.pepper is set. Because Devise is gone in 6.0 a former+ pepper can't be introspected, so when Devise is absent the task aborts until+ you confirm none was used with CONFIRM_NO_PEPPER=true. Peppered / SSO /+ non-bcrypt installs keep a custom customer_class instead (see the 5.6-to-6.0+ upgrade guide) and skip this step.++ Source rows with a blank email, or whose email is already owned by a+ different customer, abort the task with their ids — reconcile them or pass+ SKIP_INVALID_ROWS=true to skip and continue.Idempotent. The source table is left in place as a safety net — drop itmanually once the migration is verified. Override the source withdiff --git a/spree/core/lib/tasks/migrate_users_to_customers.rake b/spree/core/lib/tasks/migrate_users_to_customers.rakeindex b4c8847c60..fd14747da4 100644--- a/spree/core/lib/tasks/migrate_users_to_customers.rake+++ b/spree/core/lib/tasks/migrate_users_to_customers.rake@@ -6,15 +6,21 @@ namespace :spree do+spree_users+, override with SOURCE_USER_TABLE) into +spree_customers+ —preserving primary keys so the already-renamed +customer_id+ foreign keysstill resolve, and mapping +encrypted_password+ into +password_digest+ —- then re-points every polymorphic +user_type+ that named the old customer+ then re-points every polymorphic reference that named the old customerclass (default +Spree::User+, override with SOURCE_USER_TYPE) to- +Spree.customer_class+, and backfills +password_digest+ on+ +Spree.customer_class+ — the +user_type+ columns plus +customer_type+ on+ customer-group memberships — and backfills +password_digest+ on+spree_admin_users+ from its legacy +encrypted_password+.Passwords survive with zero resets only when no Devise pepper wasconfigured — Devise's +encrypted_password+ is a plain bcrypt digest, theexact format +has_secure_password+ reads. The task aborts if a pepper is- detected. The legacy source table is left in place as a safety net.+ detected; when Devise is absent (so a former pepper can't be introspected)+ it aborts until you confirm none was used with CONFIRM_NO_PEPPER=true.+ Source rows with a blank email, or whose email is already taken by a+ different customer, abort the task with their ids — reconcile them or pass+ SKIP_INVALID_ROWS=true to skip and continue. The legacy source table is+ left in place as a safety net.Idempotent — re-running skips rows already present in +spree_customers+.Batch size defaults to 1000 (override with BATCH_SIZE).@@ -33,12 +39,16 @@ namespace :spree doend# Peppered digests can't be verified by has_secure_password. Refuse rather- # than silently produce accounts nobody can sign into.+ # than silently produce accounts nobody can sign into. Once Devise is gone+ # a former pepper can't be introspected, so require an explicit all-clear.if defined?(Devise) && Devise.respond_to?(:pepper) && Devise.pepper.present?abort " Devise.pepper is configured — bcrypt digests can't be copied into password_digest. " \"Use the custom-model path (keep the table, alias password_digest) or force password resets."- elsif !defined?(Devise)- puts " Devise not loaded — assuming plain bcrypt digests (no pepper). If the source used a pepper, stop now."+ elsif !defined?(Devise) && ENV['CONFIRM_NO_PEPPER'] != 'true'+ abort " Devise isn't loaded, so a former Devise pepper can't be detected. A peppered digest " \+ "copied as-is can't be verified by has_secure_password — every migrated account would be " \+ "locked out silently. Re-run with CONFIRM_NO_PEPPER=true once you've confirmed the source " \+ "used no pepper, or use the custom-model path / force password resets."endcustomer_model = Spree.customer_class@@ -54,22 +64,40 @@ namespace :spree dodirect_columns = customer_model.column_names & source.column_namescopy_digest_from_encrypted = source.column_names.include?('encrypted_password') &&!direct_columns.include?('password_digest')+ has_marketing_column = customer_model.column_names.include?('accepts_email_marketing')++ # Preflight: catch rows we can't faithfully copy before writing anything, so+ # a bad row can't leave an already-renamed +customer_id+ foreign key pointing+ # at a customer that never migrated. Two kinds are rejected:+ # 1. Blank email — the target column is NOT NULL and uniquely indexed, so+ # the row can't be inserted at all.+ # 2. Email already owned by a different customer — insert_all would abort+ # the whole batch on the unique-email index.+ # Either kind aborts the task with the offending ids unless the operator+ # passes SKIP_INVALID_ROWS=true to skip them and continue.+ pending = source.where.not(id: customer_model.select(:id))+ blank_email_ids = pending.where("email IS NULL OR email = ''").pluck(:id)+ conflict_ids = pending.where("email IS NOT NULL AND email <> ''").+ where(email: customer_model.select(:email)).pluck(:id)+ invalid_ids = (blank_email_ids + conflict_ids).uniq++ if invalid_ids.any? && ENV['SKIP_INVALID_ROWS'] != 'true'+ abort " #{invalid_ids.size} source row(s) can't be migrated — " \+ "#{blank_email_ids.size} with a blank email#{blank_email_ids.any? ? " (ids: #{blank_email_ids.first(20).join(', ')})" : ''}, " \+ "#{conflict_ids.size} whose email is already taken by another customer#{conflict_ids.any? ? " (ids: #{conflict_ids.first(20).join(', ')})" : ''}. " \+ "Reconcile them, or re-run with SKIP_INVALID_ROWS=true to skip these and continue."+ endcopied = 0- skipped_blank_email = 0-- source.where.not(id: customer_model.select(:id)).in_batches(of: batch_size) do |relation|- rows = []-- relation.each do |record|- if record[:email].blank?- skipped_blank_email += 1- next- end+ pending.where.not(id: invalid_ids).in_batches(of: batch_size) do |relation|+ rows = relation.map do |record|attributes = record.attributes.slice(*direct_columns)attributes['password_digest'] = record[:encrypted_password] if copy_digest_from_encrypted- rows << attributes+ # accepts_email_marketing is NOT NULL with no DB default — coalesce so a+ # legacy NULL (or a source table lacking the column) can't break the insert.+ attributes['accepts_email_marketing'] = false if has_marketing_column && attributes['accepts_email_marketing'].nil?+ attributesendnext if rows.empty?@@ -84,13 +112,16 @@ namespace :spree do# Re-point polymorphic user references. Ids are preserved, so only the type# string changes; admin rows (Spree::AdminUser) stay put — that class name- # is unchanged in 6.0.+ # is unchanged in 6.0. Customer-group memberships store the type in the+ # already-renamed +customer_type+ column; every other table still uses+ # +user_type+/+*_type+.repointed = {- role_users: Spree::RoleUser.where(user_type: old_type).update_all(user_type: new_type),- refresh_tokens: Spree::RefreshToken.where(user_type: old_type).update_all(user_type: new_type),- user_identities: Spree::UserIdentity.where(user_type: old_type).update_all(user_type: new_type),- api_keys_created_by: Spree::ApiKey.where(created_by_type: old_type).update_all(created_by_type: new_type),- api_keys_revoked_by: Spree::ApiKey.where(revoked_by_type: old_type).update_all(revoked_by_type: new_type)+ role_users: Spree::RoleUser.where(user_type: old_type).update_all(user_type: new_type),+ refresh_tokens: Spree::RefreshToken.where(user_type: old_type).update_all(user_type: new_type),+ user_identities: Spree::UserIdentity.where(user_type: old_type).update_all(user_type: new_type),+ customer_group_users: Spree::CustomerGroupUser.where(customer_type: old_type).update_all(customer_type: new_type),+ api_keys_created_by: Spree::ApiKey.where(created_by_type: old_type).update_all(created_by_type: new_type),+ api_keys_revoked_by: Spree::ApiKey.where(revoked_by_type: old_type).update_all(revoked_by_type: new_type)}# Admins stay in spree_admin_users (in place) — backfill the digest from@@ -103,11 +134,12 @@ namespace :spree doendputs- puts " Customers copied: #{copied} (skipped #{skipped_blank_email} blank-email row(s))."+ puts " Customers copied: #{copied} (skipped #{invalid_ids.size} invalid row(s): " \+ "#{blank_email_ids.size} blank-email, #{conflict_ids.size} email-conflict)."puts " Admin password_digest backfilled: #{admin_backfilled}."puts " Re-pointed #{old_type} -> #{new_type}: " \"role_users #{repointed[:role_users]}, refresh_tokens #{repointed[:refresh_tokens]}, " \- "user_identities #{repointed[:user_identities]}, " \+ "user_identities #{repointed[:user_identities]}, customer_group_users #{repointed[:customer_group_users]}, " \"api_keys #{repointed[:api_keys_created_by] + repointed[:api_keys_revoked_by]}."puts " #{source_table} left in place — drop it once you've verified the migration."enddiff --git a/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb b/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rbindex 796079b8c6..58b5771947 100644--- a/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb+++ b/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb@@ -40,9 +40,15 @@ describe 'spree:upgrade:migrate_users_to_customers' dobefore dosubject.reenableENV['SOURCE_USER_TABLE'] = source_table+ # Devise is gone in 6.0, so the task can't introspect a former pepper — the+ # examples assert the confirmed no-pepper happy path.+ ENV['CONFIRM_NO_PEPPER'] = 'true'end- after { ENV.delete('SOURCE_USER_TABLE') }+ after do+ ENV.delete('SOURCE_USER_TABLE')+ ENV.delete('CONFIRM_NO_PEPPER')+ end# Raw handle on the legacy table — no validations, lets us set explicit ids.let(:legacy_users) { Class.new(Spree.base_class) { self.table_name = 'spree_legacy_source_users' } }@@ -54,7 +60,6 @@ describe 'spree:upgrade:migrate_users_to_customers' dolegacy_users.create!(id: 900_001, email: '[email protected]', encrypted_password: 'alice_digest',first_name: 'Alice', accepts_email_marketing: true, failed_attempts: 2)legacy_users.create!(id: 900_002, email: '[email protected]', encrypted_password: 'bob_digest')- legacy_users.create!(id: 900_003, email: '', encrypted_password: 'ghost_digest')endit 'copies rows preserving id and mapping encrypted_password to password_digest' do@@ -70,11 +75,31 @@ describe 'spree:upgrade:migrate_users_to_customers' doexpect(Spree.customer_class.exists?(900_002)).to be(true)end- it 'skips rows with a blank email' do- subject.invoke+ describe 'invalid source rows' do+ it 'aborts and copies nothing when a source row has a blank email' do+ legacy_users.create!(id: 900_010, email: '', encrypted_password: 'ghost_digest')++ expect { subject.invoke }.to raise_error(SystemExit)+ expect(Spree.customer_class.exists?(900_001)).to be(false)+ end++ it 'aborts when a source email is already owned by a different customer' do+ create(:user, email: '[email protected]')++ expect { subject.invoke }.to raise_error(SystemExit)+ end++ it 'skips invalid rows and copies the rest with SKIP_INVALID_ROWS=true' do+ legacy_users.create!(id: 900_010, email: '', encrypted_password: 'ghost_digest')+ ENV['SKIP_INVALID_ROWS'] = 'true'- expect(Spree.customer_class.exists?(900_003)).to be(false)- expect(Spree.customer_class.where(email: '')).to be_empty+ subject.invoke++ expect(Spree.customer_class.exists?(900_010)).to be(false)+ expect(Spree.customer_class.exists?(900_001)).to be(true)+ ensure+ ENV.delete('SKIP_INVALID_ROWS')+ endendit 'advances the primary key sequence past the copied ids' do@@ -97,6 +122,8 @@ describe 'spree:upgrade:migrate_users_to_customers' dolet!(:identity) { create(:user_identity).tap { |i| i.update_columns(user_type: 'Spree::User') } }let!(:role_user) { create(:role_user).tap { |ru| ru.update_columns(user_type: 'Spree::User') } }let!(:api_key) { create(:api_key, :secret).tap { |k| k.update_columns(created_by_type: 'Spree::User', created_by_id: 1) } }+ # Customer-group membership stores the type in the renamed customer_type column.+ let!(:group_membership) { create(:customer_group_user).tap { |m| m.update_columns(customer_type: 'Spree::User') } }it 'flips Spree::User references to Spree::Customer' dosubject.invoke@@ -105,6 +132,7 @@ describe 'spree:upgrade:migrate_users_to_customers' doexpect(identity.reload.user_type).to eq('Spree::Customer')expect(role_user.reload.user_type).to eq('Spree::Customer')expect(api_key.reload.created_by_type).to eq('Spree::Customer')+ expect(group_membership.reload.customer_type).to eq('Spree::Customer')endit 'leaves admin references untouched' do@@ -135,6 +163,12 @@ describe 'spree:upgrade:migrate_users_to_customers' doexpect { subject.invoke }.to raise_error(SystemExit)end+ it 'aborts when Devise is absent and no-pepper is unconfirmed' do+ ENV.delete('CONFIRM_NO_PEPPER')++ expect { subject.invoke }.to raise_error(SystemExit)+ end+it 'no-ops when the source table is absent' doENV['SOURCE_USER_TABLE'] = 'a_table_that_does_not_exist'diff --git a/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb b/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rbindex 7a9ee01b2a..a42b07a77b 100644--- a/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb+++ b/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb@@ -108,6 +108,17 @@ describe Spree::Authentication::Strategies::EmailPasswordStrategy doexpect(result).to be_successexpect(result.value).to eq(bare_user)end++ it 'authenticates without raising when the class defines the reset hook but no counter' do+ partial_user = double('customer with reset hook but no counter',+ valid_password?: true, reset_failed_attempts!: nil)+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(partial_user)++ result = strategy.authenticate++ expect(result).to be_success+ expect(result.value).to eq(partial_user)+ endendcontext 'when email is blank' dodiff --git a/spree/core/spec/support/shared_examples/account_lockout.rb b/spree/core/spec/support/shared_examples/account_lockout.rbindex 0018343f79..928421221a 100644--- a/spree/core/spec/support/shared_examples/account_lockout.rb+++ b/spree/core/spec/support/shared_examples/account_lockout.rb@@ -18,6 +18,19 @@ RSpec.shared_examples 'account lockout' doexpect(lockable.reload).to be_lockedend+ it 'still locks when a stale instance records the threshold attempt' do+ Spree::Config[:max_failed_login_attempts] = 2+ # A second handle on the same row, loaded while the counter is 0 — the row+ # lock must make its increment read the latest value rather than overwrite it.+ stale = lockable.class.find(lockable.id)++ lockable.record_failed_attempt!+ stale.record_failed_attempt!++ expect(lockable.reload).to be_locked+ expect(lockable.failed_attempts).to eq(2)+ end+it 'clears the lock and counter on reset' doSpree::Config[:max_failed_login_attempts] = 22.times { lockable.record_failed_attempt! }