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.

Add user→customer data migration path (platform-auth Phase 2)

Łukasz Adamczyk763f4e2ff62c
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.md
index 9c10a36e96..2c1fd99c16 100644
--- a/docs/plans/6.0-platform-auth.md
+++ b/docs/plans/6.0-platform-auth.md
@@ -1,10 +1,10 @@
# Platform-Owned Authentication & User Model Rename
-**Status:** In Progress (RefreshToken shipped in 5.4 ✓; Phases 1 & 3 implemented on `feature/v-3514` — gem-owned `Spree::Customer`/`Spree::AdminUser` models + `Spree.customer_class` rename + `user_id`→`customer_id`; Phase 2 data migration + Phases 4–6 pending)
+**Status:** In Progress (RefreshToken shipped in 5.4 ✓; Phases 1–3 implemented on `feature/v-3514` — gem-owned `Spree::Customer`/`Spree::AdminUser` models + `Spree.customer_class` rename + `user_id`→`customer_id`; Phase 2 data migration implemented — `spree:upgrade:migrate_users_to_customers` (Path A) + custom-model recipe (Path B); Phases 4–6 pending)
**Target:** Spree 5.4 (RefreshToken ✓) + Spree 6.0 (Devise removal, User→Customer rename)
**Depends on:** Admin SPA (6.0-admin-spa.md — removes Rails admin, kills Devise dependency) for Devise removal
**Author:** Damian + Claude
-**Last updated:** 2026-07-28
+**Last updated:** 2026-07-29
## Summary
@@ -325,13 +325,44 @@ class CreateSpreeCustomersAndAdminUsers < ActiveRecord::Migration[7.2]
end
```
-### Phase 2: Data migration (for existing Devise-based installs)
-
-Two supported paths:
-
-**Path A — move onto the gem models (recommended, default for spree-starter installs).** A rake task copies rows from the app's user table(s) into `spree_customers` / `spree_admin_users`, mapping `encrypted_password` → `password_digest`. **Passwords survive with zero resets:** Devise's `encrypted_password` is a plain bcrypt digest — the exact format `has_secure_password` reads — as long as no Devise pepper is configured (the spree-starter default). The task must abort loudly if `Devise.pepper` is set (peppered digests can't be verified by `has_secure_password`; those installs use Path B or force resets). Devise reset/remember/confirmation tokens do not carry over — `generates_token_for` replaces reset tokens, and in-flight reset emails simply expire.
-
-**Path B — keep a custom user model.** No data migration: point `Spree.customer_class` at the existing model, replace the old three-concern include set with `include Spree::CustomerMethods`, and add `has_secure_password` (works against the existing `encrypted_password` column via `alias_attribute :password_digest, :encrypted_password` or a column rename). For apps with shared auth DBs, SSO-owned user tables, or non-bcrypt setups.
+### Phase 2: Data migration (for existing Devise-based installs) — implemented on `feature/v-3514`
+
+Two supported paths, both delivered:
+
+**Path A — move onto the gem models (default for spree-starter installs).** The rake task
+`spree:upgrade:migrate_users_to_customers` (`spree/core/lib/tasks/migrate_users_to_customers.rake`,
+registered in the `5_6_to_6_0` upgrade manifest) copies the legacy customer table (default
+`spree_users`, `SOURCE_USER_TABLE`-overridable) into `spree_customers` **preserving primary keys** so
+the 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
+(`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::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 the
+legacy `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`.
+
+**Path B — keep a custom user model (documented recipe, no gem code).** No data migration and no new
+concern: point `Spree.customer_class` at the existing model, replace the old three-concern include set
+with `include Spree::CustomerMethods` (which already absorbs `UserAddress` + `UserPaymentSource`), add
+`has_secure_password validations: false`, and bridge the digest column on **that model** with
+`alias_attribute :password_digest, :encrypted_password` (or rename the column). The alias lives on the
+app model, so `Spree::Customer` is untouched — a blanket alias in `CustomerMethods` would shadow the
+default model's real `password_digest` and break `has_secure_password`, which is why it stays a recipe.
+Proven by `spec/models/spree/legacy_encrypted_password_recipe_spec.rb`. For apps with shared auth DBs,
+SSO-owned user tables, or non-bcrypt setups.
+
+**Schema note:** the two Phase-1 create migrations were merged into a single clash-aware
+`20260728000000_create_spree_customers_and_admin_users` (a non-colliding name — the old
+`create_spree_admin_users` is deduped away at `install:migrations` copy time and never runs on
+upgrades). It creates `spree_customers` fresh, and for `spree_admin_users` guards
+`create … unless table_exists?` + `add_column :password_digest unless column_exists?` (added alongside
+`encrypted_password`, never renamed, so Devise digests survive for the backfill).
### Phase 3: Rename config accessors + concerns
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 301df49b10..4405f101e9 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -408,3 +408,51 @@ same format `has_secure_password` reads — so the rake task migrating
spree-starter installs onto `spree_customers` copies it to `password_digest`
and **no customer resets their password** (task aborts loudly if
`Devise.pepper` is set).
+
+## 2026-07-29: Phase 2 user→customer data migration — copy-preserving-id, in-place admins, single clash-aware migration
+
+Implementing Phase 2 of `6.0-platform-auth.md` settled several mechanics.
+
+**Customers are a row copy, admins are in place.** The 6.0 split is already
+two-table (`spree_users`=customers, `spree_admin_users`=admins; admin-ness is a
+polymorphic `spree_role_users.user_type`, not a table). So `spree_customers` is a
+**new** table and its data comes from copying `spree_users` — it cannot be a
+`rename_table` (the create migration always runs, so the target already exists;
+fresh installs have no `spree_users`; and `spree_users` carries Devise cruft).
+`spree_admin_users` keeps its table **and** its class name `Spree::AdminUser`, so
+admins never move — the task only backfills `password_digest` from the legacy
+`encrypted_password`.
+
+**Copy preserves primary keys** so the already-renamed `customer_id` FKs
+(2026-03-16 entry) still resolve with no id remap. This is the first repo task to
+insert explicit ids, so it also **resets the Postgres sequence** afterward
+(`reset_pk_sequence!`, guarded to PG) — no prior precedent because taxon→category
+preserved 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.
+
+**Single clash-aware create migration.** The two Phase-1 create migrations merged
+into `20260728000000_create_spree_customers_and_admin_users` — a **non-colliding**
+name, because `install:migrations` de-dupes engine migrations by name and every
+existing app already has a `create_spree_admin_users`, so the gem's same-named
+migration is skipped and never runs on upgrades. The merged migration creates
+`spree_customers` cleanly and guards the admin side
+(`create … unless table_exists?`, `add_column :password_digest unless
+column_exists?`). `password_digest` is **added alongside** `encrypted_password`,
+never a rename — nothing is lost, and the backfill has both columns to read.
+
+**Path B is a recipe, not gem code.** Keeping a custom user model needs no new
+concern: on the app's own model, `include Spree::CustomerMethods` +
+`has_secure_password validations: false` + `alias_attribute :password_digest,
+:encrypted_password` (or a column rename). The alias must live on the app model —
+a blanket alias in `CustomerMethods` would shadow the default `Spree::Customer`'s
+real `password_digest` and break `has_secure_password` on it.
+
+The 5.6→6.0 upgrade guide (`docs/developer/upgrades/5.6-to-6.0.mdx`) doesn't exist
+yet (6.0 in-dev); Path A/B developer guidance currently lives in the task's `desc`,
+the `5_6_to_6_0` manifest notes, and this plan. It moves to the mdx when the full
+6.0 upgrade guide is authored.
diff --git a/spree/core/db/migrate/20260728000000_create_spree_admin_users.rb b/spree/core/db/migrate/20260728000000_create_spree_admin_users.rb
deleted file mode 100644
index b9c567768b..0000000000
--- a/spree/core/db/migrate/20260728000000_create_spree_admin_users.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-class CreateSpreeAdminUsers < ActiveRecord::Migration[7.2]
- def change
- create_table :spree_admin_users do |t|
- t.string :email, null: false
- t.string :password_digest
- t.string :first_name
- t.string :last_name
- t.string :selected_locale
- t.integer :failed_attempts
- t.datetime :locked_at
-
- if t.respond_to?(:jsonb)
- t.jsonb :public_metadata
- t.jsonb :private_metadata
- else
- t.json :public_metadata
- t.json :private_metadata
- end
-
- t.timestamps
- end
-
- add_index :spree_admin_users, :email, unique: true
- end
-end
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.rb
new file mode 100644
index 0000000000..5ddf8e81d6
--- /dev/null
+++ b/spree/core/db/migrate/20260728000000_create_spree_customers_and_admin_users.rb
@@ -0,0 +1,67 @@
+class CreateSpreeCustomersAndAdminUsers < ActiveRecord::Migration[7.2]
+ def up
+ # spree_admin_users already exists on any pre-6.0 install that split admins
+ # out. Create it only when absent, but always ensure the has_secure_password
+ # column exists. It is added alongside a legacy encrypted_password (never
+ # renamed), so Devise digests survive for the
+ # spree:upgrade:migrate_users_to_customers backfill.
+ unless table_exists?(:spree_admin_users)
+ create_table :spree_admin_users do |t|
+ t.string :email, null: false
+ t.string :password_digest
+ t.string :first_name
+ t.string :last_name
+ t.string :selected_locale
+ t.integer :failed_attempts
+ t.datetime :locked_at
+
+ json_columns(t, :public_metadata, :private_metadata)
+
+ t.timestamps
+ end
+
+ add_index :spree_admin_users, :email, unique: true
+ end
+
+ add_column :spree_admin_users, :password_digest, :string unless column_exists?(:spree_admin_users, :password_digest)
+
+ # spree_customers is new in 6.0 — always created fresh.
+ create_table :spree_customers do |t|
+ t.string :email, null: false
+ t.string :password_digest
+ t.string :first_name
+ t.string :last_name
+ t.string :phone
+ t.string :selected_locale
+ t.boolean :accepts_email_marketing
+ t.bigint :bill_address_id
+ t.bigint :ship_address_id
+ t.integer :failed_attempts
+ t.datetime :locked_at
+
+ json_columns(t, :public_metadata, :private_metadata)
+
+ t.timestamps
+ end
+
+ add_index :spree_customers, :email, unique: true
+ add_index :spree_customers, :bill_address_id
+ add_index :spree_customers, :ship_address_id
+ add_index :spree_customers, :accepts_email_marketing
+ end
+
+ def down
+ drop_table :spree_customers
+
+ # Leave spree_admin_users and its password_digest column in place — this
+ # migration may have found them already present (upgrade / dummy) and must
+ # not drop a table or column it did not create.
+ end
+
+ private
+
+ # jsonb on PostgreSQL (binary, indexable); json on MySQL/SQLite.
+ def json_columns(table, *names)
+ names.each { |name| table.respond_to?(:jsonb) ? table.jsonb(name) : table.json(name) }
+ end
+end
diff --git a/spree/core/db/migrate/20260728000001_create_spree_customers.rb b/spree/core/db/migrate/20260728000001_create_spree_customers.rb
deleted file mode 100644
index 84f550e5a1..0000000000
--- a/spree/core/db/migrate/20260728000001_create_spree_customers.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-class CreateSpreeCustomers < ActiveRecord::Migration[7.2]
- def change
- create_table :spree_customers do |t|
- t.string :email, null: false
- t.string :password_digest
- t.string :first_name
- t.string :last_name
- t.string :phone
- t.string :selected_locale
- t.boolean :accepts_email_marketing
- t.bigint :bill_address_id
- t.bigint :ship_address_id
- t.integer :failed_attempts
- t.datetime :locked_at
-
- if t.respond_to?(:jsonb)
- t.jsonb :public_metadata
- t.jsonb :private_metadata
- else
- t.json :public_metadata
- t.json :private_metadata
- end
-
- t.timestamps
- end
-
- add_index :spree_customers, :email, unique: true
- add_index :spree_customers, :bill_address_id
- add_index :spree_customers, :ship_address_id
- add_index :spree_customers, :accepts_email_marketing
- end
-end
diff --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.yml
index 346fe86f3f..e5f8ef44e8 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
@@ -52,3 +52,24 @@ steps:
Idempotent. Multi-tenant installs run the per-tenant override shipped by
spree_multi_tenant.
+
+ - id: migrate_users_to_customers
+ name: "Move users onto the gem-owned Customer/AdminUser models"
+ task: "spree:upgrade:migrate_users_to_customers"
+ notes: |
+ Copies the legacy Devise user table (default spree_users) into
+ spree_customers, preserving ids so the renamed customer_id foreign keys
+ still 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.
+
+ Precondition: NO Devise pepper. encrypted_password is a plain bcrypt digest
+ that 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.
+
+ Idempotent. The source table is left in place as a safety net — drop it
+ manually once the migration is verified. Override the source with
+ SOURCE_USER_TABLE / SOURCE_USER_TYPE and batch size with BATCH_SIZE.
diff --git a/spree/core/lib/tasks/migrate_users_to_customers.rake b/spree/core/lib/tasks/migrate_users_to_customers.rake
new file mode 100644
index 0000000000..b4c8847c60
--- /dev/null
+++ b/spree/core/lib/tasks/migrate_users_to_customers.rake
@@ -0,0 +1,115 @@
+namespace :spree do
+ namespace :upgrade do
+ desc <<~DESC
+ Moves an existing Devise-based user table onto the gem-owned auth models
+ (Spree 6.0). Copies rows from the legacy customer table (default
+ +spree_users+, override with SOURCE_USER_TABLE) into +spree_customers+ —
+ preserving primary keys so the already-renamed +customer_id+ foreign keys
+ still resolve, and mapping +encrypted_password+ into +password_digest+ —
+ then re-points every polymorphic +user_type+ that named the old customer
+ class (default +Spree::User+, override with SOURCE_USER_TYPE) to
+ +Spree.customer_class+, and backfills +password_digest+ on
+ +spree_admin_users+ from its legacy +encrypted_password+.
+
+ Passwords survive with zero resets only when no Devise pepper was
+ configured — Devise's +encrypted_password+ is a plain bcrypt digest, the
+ exact 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.
+
+ Idempotent — re-running skips rows already present in +spree_customers+.
+ Batch size defaults to 1000 (override with BATCH_SIZE).
+ DESC
+ task migrate_users_to_customers: :environment do
+ connection = ActiveRecord::Base.connection
+
+ source_table = ENV.fetch('SOURCE_USER_TABLE', 'spree_users')
+ old_type = ENV.fetch('SOURCE_USER_TYPE', 'Spree::User')
+ new_type = Spree.customer_class.to_s
+ batch_size = (ENV['BATCH_SIZE'] || 1000).to_i
+
+ unless connection.table_exists?(source_table)
+ puts " #{source_table} not found — nothing to migrate."
+ next
+ end
+
+ # Peppered digests can't be verified by has_secure_password. Refuse rather
+ # than silently produce accounts nobody can sign into.
+ 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."
+ end
+
+ customer_model = Spree.customer_class
+ admin_model = Spree.admin_user_class
+
+ # Read the legacy table by name only — the Devise-era Spree::User /
+ # Spree::LegacyUser models are gone in 6.0. Inherit from Spree.base_class
+ # so the source shares the customer table's connection (the id-exclusion
+ # subquery below spans both).
+ source = Class.new(Spree.base_class) { self.table_name = source_table }
+
+ # Copy only columns both tables share; map the digest column separately.
+ direct_columns = customer_model.column_names & source.column_names
+ copy_digest_from_encrypted = source.column_names.include?('encrypted_password') &&
+ !direct_columns.include?('password_digest')
+
+ copied = 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
+
+ attributes = record.attributes.slice(*direct_columns)
+ attributes['password_digest'] = record[:encrypted_password] if copy_digest_from_encrypted
+ rows << attributes
+ end
+
+ next if rows.empty?
+
+ customer_model.insert_all(rows)
+ copied += rows.size
+ print '.'
+ end
+
+ # insert_all writes explicit ids without advancing the Postgres sequence.
+ connection.reset_pk_sequence!(customer_model.table_name) if connection.adapter_name.match?(/postgres/i)
+
+ # 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.
+ 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)
+ }
+
+ # Admins stay in spree_admin_users (in place) — backfill the digest from
+ # the legacy column when present.
+ admin_backfilled = 0
+ if admin_model.column_names.include?('encrypted_password')
+ admin_backfilled = admin_model.where(password_digest: [nil, '']).
+ where.not(encrypted_password: [nil, '']).
+ update_all('password_digest = encrypted_password')
+ end
+
+ puts
+ puts " Customers copied: #{copied} (skipped #{skipped_blank_email} blank-email row(s))."
+ 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]}, " \
+ "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."
+ end
+ end
+end
diff --git a/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb b/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb
new file mode 100644
index 0000000000..796079b8c6
--- /dev/null
+++ b/spree/core/spec/lib/tasks/migrate_users_to_customers_spec.rb
@@ -0,0 +1,144 @@
+require 'spec_helper'
+require 'rake'
+
+describe 'spree:upgrade:migrate_users_to_customers' do
+ subject { Rake::Task[task_name] }
+
+ let(:task_name) { 'spree:upgrade:migrate_users_to_customers' }
+
+ # A dedicated, non-shared source table. The dummy already ships a (bare, empty)
+ # spree_users from the legacy 4.3 schema, so we must NOT create/drop that shared
+ # table — instead build a realistically-shaped legacy customer table and point
+ # the task at it via SOURCE_USER_TABLE. DDL lives in before/after(:all) so it
+ # sits outside the per-example transaction.
+ let(:source_table) { 'spree_legacy_source_users' }
+
+ before(:all) do
+ Rake::Task.define_task(:environment)
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'migrate_users_to_customers.rake')
+
+ ActiveRecord::Base.connection.create_table :spree_legacy_source_users, force: true do |t|
+ t.string :email
+ t.string :encrypted_password
+ t.string :first_name
+ t.string :last_name
+ t.string :phone
+ t.string :selected_locale
+ t.boolean :accepts_email_marketing
+ t.bigint :bill_address_id
+ t.bigint :ship_address_id
+ t.integer :failed_attempts
+ t.datetime :locked_at
+ t.timestamps
+ end
+ end
+
+ after(:all) do
+ ActiveRecord::Base.connection.drop_table :spree_legacy_source_users, if_exists: true
+ end
+
+ before do
+ subject.reenable
+ ENV['SOURCE_USER_TABLE'] = source_table
+ end
+
+ after { ENV.delete('SOURCE_USER_TABLE') }
+
+ # 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' } }
+
+ describe 'copying customers' do
+ # High, out-of-range ids so copied rows never collide with factory-created
+ # customers (which start their own low id sequence).
+ before do
+ legacy_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')
+ end
+
+ it 'copies rows preserving id and mapping encrypted_password to password_digest' do
+ subject.invoke
+
+ alice = Spree.customer_class.find(900_001)
+ expect(alice.email).to eq('[email protected]')
+ expect(alice.first_name).to eq('Alice')
+ expect(alice.accepts_email_marketing).to be(true)
+ expect(alice.failed_attempts).to eq(2)
+ expect(alice.password_digest).to eq('alice_digest')
+
+ expect(Spree.customer_class.exists?(900_002)).to be(true)
+ end
+
+ it 'skips rows with a blank email' do
+ subject.invoke
+
+ expect(Spree.customer_class.exists?(900_003)).to be(false)
+ expect(Spree.customer_class.where(email: '')).to be_empty
+ end
+
+ it 'advances the primary key sequence past the copied ids' do
+ subject.invoke
+
+ new_customer = Spree.customer_class.create!(email: '[email protected]', password: 'secret123')
+ expect(new_customer.id.to_i).to be > 900_002
+ end
+
+ it 'is idempotent — a re-run copies nothing new and does not error' do
+ subject.invoke
+ subject.reenable
+
+ expect { subject.invoke }.not_to change { Spree.customer_class.count }
+ end
+ end
+
+ describe 're-pointing polymorphic user_type' do
+ let!(:token) { create(:refresh_token).tap { |r| r.update_columns(user_type: 'Spree::User') } }
+ let!(: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) } }
+
+ it 'flips Spree::User references to Spree::Customer' do
+ subject.invoke
+
+ expect(token.reload.user_type).to eq('Spree::Customer')
+ expect(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')
+ end
+
+ it 'leaves admin references untouched' do
+ admin_token = create(:refresh_token, :for_admin)
+
+ subject.invoke
+
+ expect(admin_token.reload.user_type).to eq('Spree::AdminUser')
+ end
+ end
+
+ describe 'backfilling admin password_digest' do
+ let!(:admin) { create(:admin_user) }
+
+ before { admin.update_columns(encrypted_password: 'legacy_admin_digest', password_digest: nil) }
+
+ it 'copies encrypted_password into a blank password_digest in place' do
+ subject.invoke
+
+ expect(admin.reload.password_digest).to eq('legacy_admin_digest')
+ end
+ end
+
+ describe 'guards' do
+ it 'aborts when a Devise pepper is configured' do
+ stub_const('Devise', Class.new { def self.pepper; 'peppered'; end })
+
+ expect { subject.invoke }.to raise_error(SystemExit)
+ end
+
+ it 'no-ops when the source table is absent' do
+ ENV['SOURCE_USER_TABLE'] = 'a_table_that_does_not_exist'
+
+ expect { subject.invoke }.to output(/nothing to migrate/).to_stdout
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/legacy_encrypted_password_recipe_spec.rb b/spree/core/spec/models/spree/legacy_encrypted_password_recipe_spec.rb
new file mode 100644
index 0000000000..ca784b9722
--- /dev/null
+++ b/spree/core/spec/models/spree/legacy_encrypted_password_recipe_spec.rb
@@ -0,0 +1,47 @@
+require 'spec_helper'
+
+# Proves the Path B upgrade recipe (docs/plans/6.0-platform-auth.md): a custom
+# Spree.customer_class that keeps its legacy Devise `encrypted_password` column
+# works with `has_secure_password` via `alias_attribute` — no data migration and
+# no gem concern. If this breaks, the documented recipe is wrong.
+describe 'Legacy encrypted_password bridge', type: :model do
+ before(:all) do
+ ActiveRecord::Base.connection.create_table :legacy_recipe_users, force: true do |t|
+ t.string :email
+ t.string :encrypted_password
+ t.timestamps
+ end
+ end
+
+ after(:all) do
+ ActiveRecord::Base.connection.drop_table :legacy_recipe_users, if_exists: true
+ end
+
+ let(:model) do
+ Class.new(ActiveRecord::Base) do
+ self.table_name = 'legacy_recipe_users'
+ has_secure_password validations: false
+ alias_attribute :password_digest, :encrypted_password
+ end
+ end
+
+ it 'hashes a new password into the legacy encrypted_password column' do
+ user = model.create!(email: '[email protected]', password: 'secret123')
+
+ expect(user.encrypted_password).to be_present
+ expect(user.password_digest).to eq(user.encrypted_password)
+ end
+
+ it 'authenticates against the aliased column' do
+ user = model.create!(email: '[email protected]', password: 'secret123')
+
+ expect(user.authenticate('secret123')).to be_truthy
+ expect(user.authenticate('wrong')).to be(false)
+ end
+
+ it 're-authenticates a reloaded record' do
+ model.create!(email: '[email protected]', password: 'hunter2!')
+
+ expect(model.find_by(email: '[email protected]').authenticate('hunter2!')).to be_truthy
+ end
+end
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index 314a829e91..a1d2285f4f 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -31,7 +31,7 @@ module Spree
end
describe '#call' do
- subject { described_class.call(store: store, user: user, params: params) }
+ subject { described_class.call(store: store, customer: user, params: params) }
context 'without a store' do
it 'fails' do