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.

Rename User to Customer and make the auth models gem-owned

Łukasz Adamczyk443247109662
diff --git a/docs/plans/6.0-platform-auth.md b/docs/plans/6.0-platform-auth.md
index dee3c3ec47..9c10a36e96 100644
--- a/docs/plans/6.0-platform-auth.md
+++ b/docs/plans/6.0-platform-auth.md
@@ -1,6 +1,6 @@
# Platform-Owned Authentication & User Model Rename
-**Status:** In Progress (RefreshToken shipped in 5.4 ✓, rest in 6.0)
+**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)
**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
@@ -344,6 +344,15 @@ Two supported paths:
- Rename `user_id` FK → `customer_id` on 11 customer-facing tables (see decisions.md entry)
- Update `belongs_to :user` → `belongs_to :customer` on those models
+**Implementation notes (Phases 1 & 3, `feature/v-3514`):**
+- `Spree::Customer` (new `spree_customers`, complete column set) + `Spree::AdminUser` (existing `spree_admin_users` + `password_digest`) both use `has_secure_password validations: false` with a confirmation-only validation — password presence is **not** enforced at the model level (matches the prior LegacyUser default; storefront registration / admin-claim own that), so admin-created password-less accounts stay valid. `valid_password?` kept as an `authenticate` alias.
+- Prefix IDs: `cust_` (was `cus`) / `adm_` (was `admin`).
+- `Spree::UserMethods` → `Spree::CustomerMethods` (absorbs `UserAddress` + `UserPaymentSource`); constant-alias file keeps the old name. Concern made column-agnostic: password-reset token key falls back through `password_salt` → `encrypted_password` → `password_digest`; `login` write guarded by `has_attribute?`.
+- FK/association back-compat via a `Spree::DeprecatedCustomerAlias` concern (deprecated `user`/`user_id`/`:user` reader+writer) included on the 10 models; `spree_customer_group_users` is polymorphic so `user_type` → `customer_type` too. Model-scoped i18n error keys added under `spree/customer`.
+- Historical `add_*_to_spree_users` migrations now guard on `table_exists?(Spree.customer_class.table_name)` so a fresh default install (where the complete `spree_customers` is created by its own migration) skips them cleanly, while a custom user table still gets backfilled.
+- `spree/admin` left untouched (removed in 6.0) — it rides the deprecated `Spree.user_class` alias.
+- **Spree's own specs use `customer` directly, not the aliases** (aliases are only to smooth external-gem migration): factory calls migrated `user:` → `customer:` for renamed-model factories (Import/Export/Report/RoleUser/RefreshToken/StateChange/UserIdentity keep `user:`), `Spree.user_class` → `Spree.customer_class`. Core `spec/models` + `spec/services` + `spec/lib` are green (7094 examples). Remaining: first-party code `.user`/`.user_id` *reads* still on aliases (functional, warn-only) + `spree/api` & `spree/emails` spec migration/runs.
+
### Phase 4: Refresh token support
- Create `Spree::RefreshToken` model
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 9b7587ccdb..2313fab966 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -208,7 +208,7 @@ storefront customer (not an admin user).
- `spree_payment_sources.user_id` → `customer_id`
- `spree_newsletter_subscribers.user_id` → `customer_id`
- `spree_promotion_rule_users.user_id` → `customer_id`
-- `spree_customer_group_users.user_id` → `customer_id`
+- `spree_customer_group_users.user_id` → `customer_id` (polymorphic — `user_type` also renames to `customer_type` so `belongs_to :customer, polymorphic: true` resolves)
**Keep as `user_id`** (5 models — FK references Spree.admin_user_class or is polymorphic):
- `spree_imports.user_id` — admin who ran the import
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
index e6e2f22f2c..0db7ca880e 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
@@ -104,7 +104,7 @@ module Spree
when USER_TYPE_ADMIN
Spree.admin_user_class.find(user_id)
else
- Spree.user_class.find(user_id)
+ Spree.customer_class.find(user_id)
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
index d43490340f..2784fcf596 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/custom_fields_controller.rb
@@ -106,7 +106,7 @@ module Spree
def parent_route_map
@parent_route_map ||= Spree.metafields.enabled_resources.each_with_object({}) do |klass, m|
m[klass.model_name.element.to_s] = klass.name
- end.merge('customer' => Spree.user_class.name, 'category' => 'Spree::Category')
+ end.merge('customer' => Spree.customer_class.name, 'category' => 'Spree::Category')
end
# Returns the first segment whose `<segment>_id` is present in params,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb
index d6fb3e6130..da5f40a816 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers/base_controller.rb
@@ -21,7 +21,7 @@ module Spree
# global in Spree (`User.for_store` is a no-op), so the ability is
# the only boundary here.
def set_parent
- @parent = Spree.user_class.
+ @parent = Spree.customer_class.
accessible_by(current_ability, parent_ability_action).
find_by_prefix_id!(params[:customer_id])
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
index 7cefa62e44..679ce5193b 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
@@ -10,10 +10,10 @@ module Spree
before_action :require_ids!, only: [:bulk_add_to_groups, :bulk_remove_from_groups]
def create
- @resource = Spree.user_class.new(permitted_params)
+ @resource = Spree.customer_class.new(permitted_params)
# Admin-created customers don't pick a password upfront — they
# claim the account via password reset later.
- # `Spree::UserMethods` exposes `skip_password_validation` so
+ # `Spree::CustomerMethods` exposes `skip_password_validation` so
# Devise's `:validatable` lets a nil credential through on this
# code path. Storefront registration never sets the flag, so
# customer self-signup still requires a password.
@@ -63,7 +63,7 @@ module Spree
protected
def model_class
- Spree.user_class
+ Spree.customer_class
end
def serializer_class
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.rb
index 4308b227b6..8e3f647d9a 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,7 @@ module Spree
customer_param = params[:customer_id].presence || params[:user_id].presence
return unless customer_param
- Spree.user_class.find_by_param!(customer_param)
+ Spree.customer_class.find_by_param!(customer_param)
end
def order_create_params
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
index d18ce9616d..73e42a8fc0 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tags_controller.rb
@@ -19,7 +19,7 @@ module Spree
{
'Spree::Product' => 'read_products',
'Spree::Order' => 'read_orders',
- Spree.user_class.to_s => 'read_customers'
+ Spree.customer_class.to_s => 'read_customers'
}
end
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 1056efd193..6973f64037 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -43,7 +43,7 @@ module Spree
protected
# Override to use current_user from JWT authentication
- # @return [Spree.user_class]
+ # @return [Spree.customer_class]
def spree_current_user
current_user
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
index f6f6d5fa82..980bec5cbf 100644
--- a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb
@@ -119,7 +119,7 @@ module Spree
strategy_class.new(
params: params,
request_env: request.headers.env,
- user_class: Spree.user_class
+ user_class: Spree.customer_class
)
end
diff --git a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb
index 9f76905f2d..9630f5893c 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb
@@ -29,7 +29,7 @@ module Spree
end
end
- user = Spree.user_class.find_by(email: params[:email])
+ user = Spree.customer_class.find_by(email: params[:email])
if user
token = user.generate_token_for(:password_reset)
@@ -44,7 +44,7 @@ module Spree
# PATCH /api/v3/store/password_resets/:id
def update
- user = Spree.user_class.find_by_password_reset_token(params[:id])
+ user = Spree.customer_class.find_by_password_reset_token(params[:id])
unless user
return render_error(
diff --git a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
index f18e80866b..cf6b1153ed 100644
--- a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb
@@ -11,7 +11,7 @@ module Spree
# POST /api/v3/store/customers
def create
- user = Spree.user_class.new(permitted_params.except(:current_password))
+ user = Spree.customer_class.new(permitted_params.except(:current_password))
if user.save
link_matching_newsletter_subscriber!(user)
diff --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.rb
index 984d7a6324..2ad26d598b 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
@@ -14,7 +14,7 @@ module Spree
def create
subscriber = Spree::NewsletterSubscriber.subscribe(
email: params[:email],
- user: current_user,
+ customer: current_user,
store: current_store,
redirect_url: validated_redirect_url
)
diff --git a/spree/core/app/finders/spree/orders/find_current.rb b/spree/core/app/finders/spree/orders/find_current.rb
index 0e06ce2e58..b7c3e30d4d 100644
--- a/spree/core/app/finders/spree/orders/find_current.rb
+++ b/spree/core/app/finders/spree/orders/find_current.rb
@@ -11,7 +11,7 @@ module Spree
return order unless order.nil?
return if user.nil?
- incomplete_orders.order(created_at: :desc).find_by(store: store, user: user, currency: params[:currency])
+ incomplete_orders.order(created_at: :desc).find_by(store: store, customer: user, currency: params[:currency])
end
private
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 6ff12e89ff..b26e4cb244 100644
--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb
+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb
@@ -12,7 +12,7 @@ module Spree
# emails through Spree's mailer.
prepend Spree::AdminUserMethods::DeviseNotifications
- has_prefix_id :admin
+ has_prefix_id :adm
has_person_name
@@ -21,10 +21,11 @@ module Spree
# 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
- # `try` rather than `&.`: models without a password_salt method or
- # column at all (modern Devise) must fall through to encrypted_password
- # — a bare call would raise NameError before the fallback.
- try(:password_salt)&.last(10) || encrypted_password&.last(10)
+ # `try` rather than `&.`: a model that lacks the method/column entirely
+ # must fall through rather than raise NameError. `password_salt` covers
+ # has_secure_password (which derives it from password_digest);
+ # `encrypted_password` covers legacy bcrypt / Devise models.
+ try(:password_salt)&.last(10) || try(:encrypted_password)&.last(10)
end
def self.find_by_password_reset_token(token)
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
new file mode 100644
index 0000000000..ba37fa18b5
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -0,0 +1,334 @@
+module Spree
+ module CustomerMethods
+ extend ActiveSupport::Concern
+
+ include Spree::PrefixedId
+ include Spree::Metafields
+ include Spree::Metadata
+ include Spree::UserAddress
+ include Spree::UserPaymentSource
+ include Spree::UserReporting
+ include Spree::UserRoles
+ include Spree::RansackableAttributes
+ include Spree::Searchable
+ include Spree::Publishable
+
+ # Opt-in escape hatch for admin-side customer creation. When the host
+ # `Spree::User` includes Devise's `:validatable`, password presence is
+ # enforced on every create; admin-created customers don't pick a
+ # password upfront — they claim the account later via password reset.
+ # The admin Customers controller flips `skip_password_validation = true`
+ # when no password was supplied; the storefront registration path never
+ # sets it, so customer self-signup still requires a password.
+ #
+ # Prepended (not just defined) so it sits above Devise's own
+ # `password_required?` and can fall through with `super` when the flag
+ # isn't set. On `LegacyUser` (gem default, no Devise) `super` raises
+ # NoMethodError if invoked — but the early return covers the only
+ # branch that ever reaches this method on that path, and `LegacyUser`
+ # doesn't call `password_required?` at all, so the override is a no-op
+ # there.
+ module SkipPasswordValidation
+ def password_required?
+ return false if skip_password_validation && try(:encrypted_password).blank? && password.blank?
+ super
+ end
+ end
+
+ included do
+ has_prefix_id :cust # Stripe: cus_
+
+ attr_accessor :skip_password_validation
+
+ prepend SkipPasswordValidation
+
+ # Enable lifecycle events for user models
+ publishes_lifecycle_events
+
+ # Password reset token (Rails 7.1+ signed token, no DB column needed)
+ # Token auto-invalidates when password changes (salt changes)
+ # Expiration is configurable via Spree::Config.customer_password_reset_expires_in (in minutes)
+ generates_token_for :password_reset, expires_in: Spree::Config.customer_password_reset_expires_in.minutes do
+ # `try` rather than `&.`: a model that lacks the method/column entirely
+ # must fall through rather than raise NameError. `password_salt` covers
+ # has_secure_password (which derives it from password_digest);
+ # `encrypted_password` covers legacy bcrypt / Devise models.
+ try(:password_salt)&.last(10) || try(:encrypted_password)&.last(10)
+ end
+
+ # we need to have this callback before any dependent: :destroy associations
+ # https://github.com/rails/rails/issues/3458
+ before_validation :clone_billing_address, if: :use_billing?
+ before_destroy :check_completed_orders
+
+ after_save_commit :sync_newsletter_subscription_with_marketing_consent,
+ if: :saved_change_to_accepts_email_marketing?
+
+ attr_accessor :use_billing
+
+ has_person_name
+ normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }
+ acts_as_taggable_on :tags
+
+ def tags=(tags)
+ self.tag_list = tags
+ end
+
+ #
+ # Associations
+ #
+ has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :customer_id, dependent: :destroy
+ has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'
+ has_many :orders, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :carts, -> { incomplete }, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :completed_orders, -> { complete }, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :customer_id, dependent: :destroy
+ has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :customer_id, dependent: :destroy
+ has_many :wished_items, through: :wishlists, source: :wished_items
+ has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :customer_id
+ has_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :customer_id, dependent: :destroy
+ has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', as: :customer, dependent: :destroy
+ has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'
+ has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
+ belongs_to :ship_address, class_name: 'Spree::Address', optional: true
+ belongs_to :bill_address, class_name: 'Spree::Address', optional: true
+
+ # Replaces the customer's group membership. Accepts both prefixed IDs and
+ # raw integer IDs. Only groups belonging to the current store are
+ # assigned — ids from another store are dropped, preventing cross-store
+ # membership. Mirrors +Spree::Product#category_ids=+.
+ def customer_group_ids=(ids)
+ decoded_ids = Array(ids).filter_map do |id|
+ id.to_s.include?('_') ? Spree::CustomerGroup.decode_prefixed_id(id) : id
+ end
+ super(Spree::CustomerGroup.for_store(Spree::Current.store).where(id: decoded_ids).ids)
+ end
+
+ #
+ # Attachments
+ #
+ has_one_attached :avatar, service: Spree.public_storage_service_name
+ has_rich_text :internal_note
+
+ #
+ # Attributes
+ #
+ attr_accessor :confirm_email, :terms_of_service
+
+ 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
+
+ def self.search(query)
+ return none if query.blank?
+
+ # `search_condition` handles sanitization itself — it escapes LIKE
+ # wildcards for plain columns and compares encrypted columns by
+ # equality. Pass the raw query so it can branch correctly.
+ conditions = []
+ conditions << search_condition(self, :email, query)
+ conditions << search_condition(self, :first_name, query)
+ conditions << search_condition(self, :last_name, query)
+
+ full_name = NameOfPerson::PersonName.full(query.to_s.strip)
+
+ if full_name.first.present? && full_name.last.present?
+ conditions << search_condition(self, :first_name, full_name.first)
+ conditions << search_condition(self, :last_name, full_name.last)
+ end
+
+ where(conditions.reduce(:or))
+ end
+
+ # Backward compatibility alias — remove in Spree 6.0
+ def self.multi_search(query) = search(query)
+
+ self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles orders customer_groups]
+ self.whitelisted_ransackable_attributes = %w[id email first_name last_name phone accepts_email_marketing
+ created_at updated_at last_sign_in_at]
+ self.whitelisted_ransackable_scopes = %w[search multi_search with_min_total_spent]
+
+ scope :with_min_total_spent, ->(amount) {
+ joins(:orders).where(spree_orders: { state: 'complete' }).
+ group("#{table_name}.id").
+ having('SUM(spree_orders.total) >= ?', amount.to_d)
+ }
+
+ # Precomputes orders_count, total_spent, and last_order_completed_at via a
+ # single aggregate join so list endpoints avoid 4 queries per user. The
+ # values land on the user as virtual attributes.
+ scope :with_order_aggregates, -> {
+ order_table = Spree::Order.table_name
+ select(
+ "#{table_name}.*, " \
+ "COALESCE(orders_agg.orders_count, 0) AS orders_count, " \
+ "COALESCE(orders_agg.total_spent, 0) AS total_spent, " \
+ "orders_agg.last_order_completed_at AS last_order_completed_at"
+ ).joins(
+ "LEFT JOIN (" \
+ "SELECT customer_id, COUNT(*) AS orders_count, SUM(total) AS total_spent, MAX(completed_at) AS last_order_completed_at " \
+ "FROM #{order_table} " \
+ "WHERE state = 'complete' AND customer_id IS NOT NULL " \
+ "GROUP BY customer_id" \
+ ") orders_agg ON orders_agg.customer_id = #{table_name}.id"
+ )
+ }
+
+ def self.with_email(query)
+ where("#{table_name}.email LIKE ?", "%#{query}%")
+ end
+
+ def self.with_address(query, address = :ship_address)
+ left_outer_joins(address).
+ where("#{Spree::Address.table_name}.firstname like ?", "%#{query}%").
+ or(left_outer_joins(address).where("#{Spree::Address.table_name}.lastname like ?", "%#{query}%"))
+ end
+
+ def self.with_email_or_address(email, address)
+ left_outer_joins(:addresses).
+ where("#{Spree::Address.table_name}.firstname LIKE ? or #{Spree::Address.table_name}.lastname LIKE ? or #{table_name}.email LIKE ?",
+ "%#{address}%", "%#{address}%", "%#{email}%")
+ end
+
+ # We override this method because we cannot use for_store on users because it will return admin users
+ def self.for_store(store)
+ self
+ end
+ end
+
+ # Returns the last incomplete spree order for the current store
+ # @param [Spree::Store] store
+ # @param [Hash] options
+ # @option options [Array<Symbol>] :includes
+ # @return [Spree::Order]
+ def last_incomplete_spree_order(store, options = {})
+ orders.where(store: store).incomplete.not_canceled.
+ includes(options[:includes]).
+ order('created_at DESC').
+ first
+ end
+
+ # Returns the total available store credit for the current store per currency
+ # @param [Spree::Store] store
+ # @param [String] currency
+ # @return [Float]
+ def total_available_store_credit(currency = nil, store = nil)
+ store ||= Store.default
+ currency ||= store.default_currency
+
+ # When the association is already loaded (e.g. preloaded via the admin
+ # API's scope_includes), filter in memory to avoid an N+1 — but mirror
+ # the query branch exactly: non-gift-card credits, scoped to the store
+ # and currency. A gift card is identified by its originator_type.
+ if store_credits.loaded?
+ store_credits.
+ select { |sc| sc.originator_type != 'Spree::GiftCard' && sc.store_id.to_s == store.id.to_s && sc.currency == currency }.
+ sum(&:amount_remaining)
+ else
+ store_credits.without_gift_card.for_store(store).where(currency: currency).to_a.sum(&:amount_remaining)
+ end
+ end
+
+ # Returns the available store credits for the current store per currency
+ # @param [Spree::Store] store
+ # @return [Array<Spree::Money>]
+ def available_store_credits(store)
+ store ||= Store.default
+
+ store_credits.for_store(store).pluck(:currency).uniq.each_with_object([]) do |currency, arr|
+ arr << Spree::Money.new(total_available_store_credit(currency, store), currency: currency)
+ end
+ end
+
+ # Returns the default wishlist for the current store
+ # if no default wishlist exists, it creates one
+ # @param [Spree::Store] current_store
+ # @return [Spree::Wishlist]
+ def default_wishlist_for_store(current_store)
+ wishlists.find_by(is_default: true, store_id: current_store.id) || ActiveRecord::Base.connected_to(role: :writing) do
+ wishlists.create!(store: current_store, is_default: true, name: Spree.t(:default_wishlist_name))
+ end
+ end
+
+ # Returns true if the user can be deleted
+ # Customers can be deleted if they have no completed orders
+ # @return [Boolean]
+ def can_be_deleted?
+ orders.complete.none?
+ end
+
+ # Returns the CSV row representation of the user
+ # @param [Spree::Store] store
+ # @return [Array<String>]
+ def to_csv(_store = nil)
+ Spree::CSV::CustomerPresenter.new(self).call
+ end
+
+ # Returns the full name of the user
+ # @return [String]
+ def full_name
+ name&.full
+ end
+
+ def event_serializer_class
+ 'Spree::Api::V3::CustomerSerializer'.safe_constantize
+ end
+
+ def event_prefix
+ if self.class == Spree.admin_user_class && Spree.admin_user_class != Spree.customer_class
+ 'admin'
+ else
+ 'user'
+ end
+ end
+
+ # @param store [Spree::Store] store to scope the lookup to; defaults to the current store
+ # @return [Spree::NewsletterSubscriber, nil] this user's newsletter subscriber for the given store
+ def newsletter_subscriber(store = Spree::Current.store)
+ return unless store
+
+ Spree::NewsletterSubscriber.for_store(store).find_by(customer_id: id)
+ end
+
+ private
+
+ def check_completed_orders
+ raise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?
+ end
+
+ def clone_billing_address
+ if bill_address && ship_address.nil?
+ self.ship_address = bill_address.clone
+ else
+ ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')
+ end
+ true
+ end
+
+ def use_billing?
+ use_billing.in?([true, 'true', '1'])
+ end
+
+ # Scrambles the email and names of the user
+ def scramble_email_and_names
+ self.email = "#{SecureRandom.uuid}@example.net"
+ self.first_name = 'Deleted'
+ self.last_name = 'User'
+ self.login = email if has_attribute?(:login)
+ save
+ end
+
+ def sync_newsletter_subscription_with_marketing_consent
+ if accepts_email_marketing?
+ Spree::NewsletterSubscriber.subscribe(email: email, customer: self)
+ else
+ # Only remove the subscriber for the current store, mirroring the store-scoped subscribe path.
+ newsletter_subscriber&.destroy
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/deprecated_customer_alias.rb b/spree/core/app/models/concerns/spree/deprecated_customer_alias.rb
new file mode 100644
index 0000000000..09a66e9555
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/deprecated_customer_alias.rb
@@ -0,0 +1,22 @@
+module Spree
+ # Deprecation shim for the 6.0 user_id -> customer_id / belongs_to :user -> :customer
+ # rename. Included by customer-facing models so `.user` / `.user_id` keep working
+ # for one release. Remove in Spree 6.1.
+ module DeprecatedCustomerAlias
+ extend ActiveSupport::Concern
+
+ included do
+ alias_attribute :user_id, :customer_id
+ end
+
+ def user
+ Spree::Deprecation.warn("#{self.class}#user is deprecated and will be removed in Spree 6.1. Use #customer instead.") if defined?(Spree::Deprecation)
+ customer
+ end
+
+ def user=(value)
+ Spree::Deprecation.warn("#{self.class}#user= is deprecated and will be removed in Spree 6.1. Use #customer= instead.") if defined?(Spree::Deprecation)
+ self.customer = value
+ end
+ end
+end
diff --git a/spree/core/app/models/concerns/spree/user_address.rb b/spree/core/app/models/concerns/spree/user_address.rb
index 832a53fc6a..088f3c6703 100644
--- a/spree/core/app/models/concerns/spree/user_address.rb
+++ b/spree/core/app/models/concerns/spree/user_address.rb
@@ -16,7 +16,7 @@ module Spree
accepts_nested_attributes_for :ship_address, :bill_address
has_many :addresses, -> { where(deleted_at: nil).order('updated_at DESC') },
- class_name: 'Spree::Address', foreign_key: :user_id
+ class_name: 'Spree::Address', foreign_key: :customer_id
validate :address_not_associated_with_other_user, :address_not_deprecated_in_completed_order
@@ -45,8 +45,8 @@ module Spree
private
def address_not_associated_with_other_user
- errors.add(:bill_address_id, :belongs_to_other_user) if bill_address&.user_id && self != bill_address&.user
- errors.add(:ship_address_id, :belongs_to_other_user) if ship_address&.user_id && self != ship_address&.user
+ errors.add(:bill_address_id, :belongs_to_other_user) if bill_address&.customer_id && self != bill_address&.customer
+ errors.add(:ship_address_id, :belongs_to_other_user) if ship_address&.customer_id && self != ship_address&.customer
end
def address_not_deprecated_in_completed_order
diff --git a/spree/core/app/models/concerns/spree/user_methods.rb b/spree/core/app/models/concerns/spree/user_methods.rb
index 7ff3e11ab3..cf0a4cc1b9 100644
--- a/spree/core/app/models/concerns/spree/user_methods.rb
+++ b/spree/core/app/models/concerns/spree/user_methods.rb
@@ -1,332 +1,7 @@
module Spree
- module UserMethods
- extend ActiveSupport::Concern
-
- include Spree::PrefixedId
- include Spree::Metafields
- include Spree::Metadata
- include Spree::UserPaymentSource
- include Spree::UserReporting
- include Spree::UserRoles
- include Spree::RansackableAttributes
- include Spree::Searchable
- include Spree::Publishable
-
- # Opt-in escape hatch for admin-side customer creation. When the host
- # `Spree::User` includes Devise's `:validatable`, password presence is
- # enforced on every create; admin-created customers don't pick a
- # password upfront — they claim the account later via password reset.
- # The admin Customers controller flips `skip_password_validation = true`
- # when no password was supplied; the storefront registration path never
- # sets it, so customer self-signup still requires a password.
- #
- # Prepended (not just defined) so it sits above Devise's own
- # `password_required?` and can fall through with `super` when the flag
- # isn't set. On `LegacyUser` (gem default, no Devise) `super` raises
- # NoMethodError if invoked — but the early return covers the only
- # branch that ever reaches this method on that path, and `LegacyUser`
- # doesn't call `password_required?` at all, so the override is a no-op
- # there.
- module SkipPasswordValidation
- def password_required?
- return false if skip_password_validation && encrypted_password.blank? && password.blank?
- super
- end
- end
-
- included do
- has_prefix_id :cus # Stripe: cus_
-
- attr_accessor :skip_password_validation
-
- prepend SkipPasswordValidation
-
- # Enable lifecycle events for user models
- publishes_lifecycle_events
-
- # Password reset token (Rails 7.1+ signed token, no DB column needed)
- # Token auto-invalidates when password changes (salt changes)
- # Expiration is configurable via Spree::Config.customer_password_reset_expires_in (in minutes)
- generates_token_for :password_reset, expires_in: Spree::Config.customer_password_reset_expires_in.minutes do
- # `try` rather than `&.`: models without a password_salt method or
- # column at all (modern Devise) must fall through to encrypted_password
- # — a bare call would raise NameError before the fallback.
- try(:password_salt)&.last(10) || encrypted_password&.last(10)
- end
-
- # we need to have this callback before any dependent: :destroy associations
- # https://github.com/rails/rails/issues/3458
- before_validation :clone_billing_address, if: :use_billing?
- before_destroy :check_completed_orders
-
- after_save_commit :sync_newsletter_subscription_with_marketing_consent,
- if: :saved_change_to_accepts_email_marketing?
-
- attr_accessor :use_billing
-
- has_person_name
- normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }
- acts_as_taggable_on :tags
-
- def tags=(tags)
- self.tag_list = tags
- end
-
- #
- # Associations
- #
- has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :user_id, dependent: :destroy
- has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'
- has_many :orders, foreign_key: :user_id, class_name: 'Spree::Order'
- has_many :carts, -> { incomplete }, foreign_key: :user_id, class_name: 'Spree::Order'
- has_many :completed_orders, -> { complete }, foreign_key: :user_id, class_name: 'Spree::Order'
- has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :user_id, dependent: :destroy
- has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :user_id, dependent: :destroy
- has_many :wished_items, through: :wishlists, source: :wished_items
- has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :user_id
- has_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :user_id, dependent: :destroy
- has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', foreign_key: :user_id, as: :user, dependent: :destroy
- has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'
- has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
- belongs_to :ship_address, class_name: 'Spree::Address', optional: true
- belongs_to :bill_address, class_name: 'Spree::Address', optional: true
-
- # Replaces the customer's group membership. Accepts both prefixed IDs and
- # raw integer IDs. Only groups belonging to the current store are
- # assigned — ids from another store are dropped, preventing cross-store
- # membership. Mirrors +Spree::Product#category_ids=+.
- def customer_group_ids=(ids)
- decoded_ids = Array(ids).filter_map do |id|
- id.to_s.include?('_') ? Spree::CustomerGroup.decode_prefixed_id(id) : id
- end
- super(Spree::CustomerGroup.for_store(Spree::Current.store).where(id: decoded_ids).ids)
- end
-
- #
- # Attachments
- #
- has_one_attached :avatar, service: Spree.public_storage_service_name
- has_rich_text :internal_note
-
- #
- # Attributes
- #
- attr_accessor :confirm_email, :terms_of_service
-
- 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
-
- def self.search(query)
- return none if query.blank?
-
- # `search_condition` handles sanitization itself — it escapes LIKE
- # wildcards for plain columns and compares encrypted columns by
- # equality. Pass the raw query so it can branch correctly.
- conditions = []
- conditions << search_condition(self, :email, query)
- conditions << search_condition(self, :first_name, query)
- conditions << search_condition(self, :last_name, query)
-
- full_name = NameOfPerson::PersonName.full(query.to_s.strip)
-
- if full_name.first.present? && full_name.last.present?
- conditions << search_condition(self, :first_name, full_name.first)
- conditions << search_condition(self, :last_name, full_name.last)
- end
-
- where(conditions.reduce(:or))
- end
-
- # Backward compatibility alias — remove in Spree 6.0
- def self.multi_search(query) = search(query)
-
- self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles orders customer_groups]
- self.whitelisted_ransackable_attributes = %w[id email first_name last_name phone accepts_email_marketing
- created_at updated_at last_sign_in_at]
- self.whitelisted_ransackable_scopes = %w[search multi_search with_min_total_spent]
-
- scope :with_min_total_spent, ->(amount) {
- joins(:orders).where(spree_orders: { state: 'complete' }).
- group("#{table_name}.id").
- having('SUM(spree_orders.total) >= ?', amount.to_d)
- }
-
- # Precomputes orders_count, total_spent, and last_order_completed_at via a
- # single aggregate join so list endpoints avoid 4 queries per user. The
- # values land on the user as virtual attributes.
- scope :with_order_aggregates, -> {
- order_table = Spree::Order.table_name
- select(
- "#{table_name}.*, " \
- "COALESCE(orders_agg.orders_count, 0) AS orders_count, " \
- "COALESCE(orders_agg.total_spent, 0) AS total_spent, " \
- "orders_agg.last_order_completed_at AS last_order_completed_at"
- ).joins(
- "LEFT JOIN (" \
- "SELECT user_id, COUNT(*) AS orders_count, SUM(total) AS total_spent, MAX(completed_at) AS last_order_completed_at " \
- "FROM #{order_table} " \
- "WHERE state = 'complete' AND user_id IS NOT NULL " \
- "GROUP BY user_id" \
- ") orders_agg ON orders_agg.user_id = #{table_name}.id"
- )
- }
-
- def self.with_email(query)
- where("#{table_name}.email LIKE ?", "%#{query}%")
- end
-
- def self.with_address(query, address = :ship_address)
- left_outer_joins(address).
- where("#{Spree::Address.table_name}.firstname like ?", "%#{query}%").
- or(left_outer_joins(address).where("#{Spree::Address.table_name}.lastname like ?", "%#{query}%"))
- end
-
- def self.with_email_or_address(email, address)
- left_outer_joins(:addresses).
- where("#{Spree::Address.table_name}.firstname LIKE ? or #{Spree::Address.table_name}.lastname LIKE ? or #{table_name}.email LIKE ?",
- "%#{address}%", "%#{address}%", "%#{email}%")
- end
-
- # We override this method because we cannot use for_store on users because it will return admin users
- def self.for_store(store)
- self
- end
- end
-
- # Returns the last incomplete spree order for the current store
- # @param [Spree::Store] store
- # @param [Hash] options
- # @option options [Array<Symbol>] :includes
- # @return [Spree::Order]
- def last_incomplete_spree_order(store, options = {})
- orders.where(store: store).incomplete.not_canceled.
- includes(options[:includes]).
- order('created_at DESC').
- first
- end
-
- # Returns the total available store credit for the current store per currency
- # @param [Spree::Store] store
- # @param [String] currency
- # @return [Float]
- def total_available_store_credit(currency = nil, store = nil)
- store ||= Store.default
- currency ||= store.default_currency
-
- # When the association is already loaded (e.g. preloaded via the admin
- # API's scope_includes), filter in memory to avoid an N+1 — but mirror
- # the query branch exactly: non-gift-card credits, scoped to the store
- # and currency. A gift card is identified by its originator_type.
- if store_credits.loaded?
- store_credits.
- select { |sc| sc.originator_type != 'Spree::GiftCard' && sc.store_id.to_s == store.id.to_s && sc.currency == currency }.
- sum(&:amount_remaining)
- else
- store_credits.without_gift_card.for_store(store).where(currency: currency).to_a.sum(&:amount_remaining)
- end
- end
-
- # Returns the available store credits for the current store per currency
- # @param [Spree::Store] store
- # @return [Array<Spree::Money>]
- def available_store_credits(store)
- store ||= Store.default
-
- store_credits.for_store(store).pluck(:currency).uniq.each_with_object([]) do |currency, arr|
- arr << Spree::Money.new(total_available_store_credit(currency, store), currency: currency)
- end
- end
-
- # Returns the default wishlist for the current store
- # if no default wishlist exists, it creates one
- # @param [Spree::Store] current_store
- # @return [Spree::Wishlist]
- def default_wishlist_for_store(current_store)
- wishlists.find_by(is_default: true, store_id: current_store.id) || ActiveRecord::Base.connected_to(role: :writing) do
- wishlists.create!(store: current_store, is_default: true, name: Spree.t(:default_wishlist_name))
- end
- end
-
- # Returns true if the user can be deleted
- # Customers can be deleted if they have no completed orders
- # @return [Boolean]
- def can_be_deleted?
- orders.complete.none?
- end
-
- # Returns the CSV row representation of the user
- # @param [Spree::Store] store
- # @return [Array<String>]
- def to_csv(_store = nil)
- Spree::CSV::CustomerPresenter.new(self).call
- end
-
- # Returns the full name of the user
- # @return [String]
- def full_name
- name&.full
- end
-
- def event_serializer_class
- 'Spree::Api::V3::CustomerSerializer'.safe_constantize
- end
-
- def event_prefix
- if self.class == Spree.admin_user_class && Spree.admin_user_class != Spree.user_class
- 'admin'
- else
- 'user'
- end
- end
-
- # @param store [Spree::Store] store to scope the lookup to; defaults to the current store
- # @return [Spree::NewsletterSubscriber, nil] this user's newsletter subscriber for the given store
- def newsletter_subscriber(store = Spree::Current.store)
- return unless store
-
- Spree::NewsletterSubscriber.for_store(store).find_by(user_id: id)
- end
-
- private
-
- def check_completed_orders
- raise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?
- end
-
- def clone_billing_address
- if bill_address && ship_address.nil?
- self.ship_address = bill_address.clone
- else
- ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')
- end
- true
- end
-
- def use_billing?
- use_billing.in?([true, 'true', '1'])
- end
-
- # Scrambles the email and names of the user
- def scramble_email_and_names
- self.email = "#{SecureRandom.uuid}@example.net"
- self.first_name = 'Deleted'
- self.last_name = 'User'
- self.login = email
- save
- end
-
- def sync_newsletter_subscription_with_marketing_consent
- if accepts_email_marketing?
- Spree::NewsletterSubscriber.subscribe(email: email, user: self)
- else
- # Only remove the subscriber for the current store, mirroring the store-scoped subscribe path.
- newsletter_subscriber&.destroy
- end
- end
- end
+ # Deprecation alias for Spree::CustomerMethods, renamed from Spree::UserMethods in 6.0.
+ # True constant alias — the underlying module, its associations, and prefix (cust)
+ # are all Spree::CustomerMethods. Remove in Spree 6.1.
+ UserMethods = CustomerMethods
+ Spree::Deprecation.warn('Spree::UserMethods is deprecated and will be removed in Spree 6.1. Use Spree::CustomerMethods instead.')
end
diff --git a/spree/core/app/models/concerns/spree/user_payment_source.rb b/spree/core/app/models/concerns/spree/user_payment_source.rb
index eb7b69ad07..40a01927c5 100644
--- a/spree/core/app/models/concerns/spree/user_payment_source.rb
+++ b/spree/core/app/models/concerns/spree/user_payment_source.rb
@@ -3,7 +3,7 @@ module Spree
extend ActiveSupport::Concern
included do
- has_many :credit_cards, class_name: 'Spree::CreditCard', foreign_key: :user_id, dependent: :destroy
+ has_many :credit_cards, class_name: 'Spree::CreditCard', foreign_key: :customer_id, dependent: :destroy
has_many :payment_setup_sessions, class_name: 'Spree::PaymentSetupSession', foreign_key: :customer_id, dependent: :destroy
def default_credit_card
diff --git a/spree/core/app/models/spree/ability.rb b/spree/core/app/models/spree/ability.rb
index 601730c794..0ca5c80ba9 100644
--- a/spree/core/app/models/spree/ability.rb
+++ b/spree/core/app/models/spree/ability.rb
@@ -24,7 +24,7 @@ module Spree
def initialize(user, options = {})
alias_cancan_delete_action
- @user = user || Spree.user_class.new
+ @user = user || Spree.customer_class.new
@store = options[:store] || Spree::Current.store
apply_permissions_from_sets
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index dfc37a6036..e794a80691 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -26,7 +26,7 @@ module Spree
# we're not freezing this on purpose so developers can extend and manage
# those attributes depending of the logic of their applications
ADDRESS_FIELDS = %w(firstname lastname company address1 address2 city state zipcode country phone)
- EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label user_id public_metadata private_metadata)
+ EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label customer_id public_metadata private_metadata)
if defined?(Spree::Security::Addresses)
include Spree::Security::Addresses
end
@@ -42,7 +42,8 @@ module Spree
belongs_to :country, class_name: 'Spree::Country'
belongs_to :state, class_name: 'Spree::State', optional: true
# we need a safe operator here as Address is added to metafield_enabled_resources in Engine
- belongs_to :user, class_name: Spree.user_class&.name, optional: true, touch: true
+ belongs_to :customer, class_name: Spree.customer_class&.name, optional: true, touch: true
+ include Spree::DeprecatedCustomerAlias
has_many :shipments, inverse_of: :address
@@ -68,7 +69,7 @@ module Spree
validate :address_validators, on: [:create, :update]
validates :label, uniqueness: { conditions: -> { where(deleted_at: nil) },
- scope: :user_id,
+ scope: :customer_id,
case_sensitive: false,
allow_blank: true,
allow_nil: true }
@@ -97,7 +98,7 @@ module Spree
end
self.whitelisted_ransackable_attributes = ADDRESS_FIELDS
- self.whitelisted_ransackable_associations = %w[country state user]
+ self.whitelisted_ransackable_associations = %w[country state customer]
def self.required_fields
Spree::Address.validators.map do |v|
@@ -367,7 +368,7 @@ module Spree
end
def unassign_from_incomplete_orders
- orders = Spree::Order.incomplete.where(user_id: user_id)
+ orders = Spree::Order.incomplete.where(customer_id: customer_id)
orders.where(ship_address_id: id).update_all(ship_address_id: nil, state: 'address', updated_at: Time.current)
orders.where(bill_address_id: id).update_all(bill_address_id: nil, state: 'address', updated_at: Time.current)
end
diff --git a/spree/core/app/models/spree/admin_user.rb b/spree/core/app/models/spree/admin_user.rb
new file mode 100644
index 0000000000..8f3e4fec1d
--- /dev/null
+++ b/spree/core/app/models/spree/admin_user.rb
@@ -0,0 +1,41 @@
+# Default staff/admin model.
+# Ships in the gem with has_secure_password on the existing spree_admin_users table.
+module Spree
+ class AdminUser < Spree.base_class
+ self.table_name = 'spree_admin_users'
+
+ has_secure_password validations: false
+
+ include Spree::AdminUserMethods
+
+ validates :email, presence: true, uniqueness: { case_sensitive: false }
+ validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: true
+
+ attribute :failed_attempts, :integer, default: 0
+
+ # Back-compat with callers and auth strategies that check +valid_password?+.
+ # Guards a blank digest (password-less accounts) so it returns false instead
+ # of raising BCrypt::Errors::InvalidHash on older Rails/bcrypt versions.
+ # @param password [String]
+ # @return [Boolean]
+ def valid_password?(password)
+ return false if password_digest.blank?
+
+ authenticate(password).present?
+ end
+
+ # @return [Boolean] whether the account is currently locked out
+ def locked?
+ locked_at.present? && locked_at > 30.minutes.ago
+ end
+
+ def record_failed_attempt!
+ increment!(:failed_attempts)
+ update!(locked_at: Time.current) if failed_attempts >= 5
+ end
+
+ def reset_failed_attempts!
+ update!(failed_attempts: 0, locked_at: nil)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb b/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
index 6b332ab0ec..2118227d23 100644
--- a/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
+++ b/spree/core/app/models/spree/authentication/strategies/base_strategy.rb
@@ -7,7 +7,7 @@ module Spree
def initialize(params:, request_env:, user_class: nil)
@params = params
@request_env = request_env
- @user_class = user_class || Spree.user_class
+ @user_class = user_class || Spree.customer_class
end
# Returns Result object with user on success
diff --git a/spree/core/app/models/spree/credit_card.rb b/spree/core/app/models/spree/credit_card.rb
index eaa28beafe..d5faa91188 100644
--- a/spree/core/app/models/spree/credit_card.rb
+++ b/spree/core/app/models/spree/credit_card.rb
@@ -13,7 +13,8 @@ module Spree
acts_as_paranoid
belongs_to :payment_method
- belongs_to :user, class_name: Spree.user_class.to_s, foreign_key: 'user_id', optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
+ include Spree::DeprecatedCustomerAlias
belongs_to :gateway_customer, class_name: 'Spree::GatewayCustomer', optional: true
has_many :payments, as: :source
diff --git a/spree/core/app/models/spree/customer.rb b/spree/core/app/models/spree/customer.rb
new file mode 100644
index 0000000000..839d660ded
--- /dev/null
+++ b/spree/core/app/models/spree/customer.rb
@@ -0,0 +1,48 @@
+# Default storefront customer model.
+#
+# Ships in the gem with has_secure_password; apps needing extra columns add their
+# own migrations against spree_customers or point Spree.customer_class at a custom
+# model that includes Spree::CustomerMethods.
+module Spree
+ class Customer < Spree.base_class
+ self.table_name = 'spree_customers'
+
+ # `validations: false` — password presence is not enforced at the model level
+ # (mirrors the previous LegacyUser default); storefront registration owns that
+ # requirement, and admin-created customers claim their account via password reset.
+ has_secure_password validations: false
+
+ include Spree::CustomerMethods
+
+ validates :email, presence: true, uniqueness: { case_sensitive: false }
+ validates :password, confirmation: true, length: { maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED }, allow_blank: true
+
+ attribute :failed_attempts, :integer, default: 0
+ attribute :accepts_email_marketing, :boolean, default: false
+
+ # Back-compat with callers and auth strategies that check +valid_password?+.
+ # Guards a blank digest (password-less accounts) so it returns false instead
+ # of raising BCrypt::Errors::InvalidHash on older Rails/bcrypt versions.
+ # @param password [String]
+ # @return [Boolean]
+ def valid_password?(password)
+ return false if password_digest.blank?
+
+ authenticate(password).present?
+ end
+
+ # @return [Boolean] whether the account is currently locked out
+ def locked?
+ locked_at.present? && locked_at > 30.minutes.ago
+ end
+
+ def record_failed_attempt!
+ increment!(:failed_attempts)
+ update!(locked_at: Time.current) if failed_attempts >= 5
+ end
+
+ def reset_failed_attempts!
+ update!(failed_attempts: 0, locked_at: nil)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/customer_group.rb b/spree/core/app/models/spree/customer_group.rb
index cbc0b24899..ead3e027a1 100644
--- a/spree/core/app/models/spree/customer_group.rb
+++ b/spree/core/app/models/spree/customer_group.rb
@@ -9,12 +9,12 @@ module Spree
#
belongs_to :store, class_name: 'Spree::Store', inverse_of: :customer_groups
has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', dependent: :destroy
- has_many :users, through: :customer_group_users, source: :user, source_type: Spree.user_class.to_s
+ has_many :users, through: :customer_group_users, source: :customer, source_type: Spree.customer_class.to_s
# `customers` is the public name across the v3 API; declaring it as its
# own association (rather than `alias_method`) is what lets `customer_ids=`
# exist and what makes the `PrefixedId` auto-decoder in `assign_attributes`
# recognise the key — that lookup keys off `reflect_on_association(:customers)`.
- has_many :customers, through: :customer_group_users, source: :user, source_type: Spree.user_class.to_s
+ has_many :customers, through: :customer_group_users, source: :customer, source_type: Spree.customer_class.to_s
#
# Validations
@@ -46,10 +46,10 @@ module Spree
return 0 if user_ids.empty?
# Get existing user IDs to avoid duplicates
- existing_user_ids = customer_group_users.where(user_id: user_ids).pluck(:user_id).map(&:to_s).to_set
+ existing_user_ids = customer_group_users.where(customer_id: user_ids).pluck(:customer_id).map(&:to_s).to_set
now = Time.current
- user_type = Spree.user_class.to_s
+ user_type = Spree.customer_class.to_s
records_to_insert = user_ids.filter_map do |user_id|
next if existing_user_ids.include?(user_id)
@@ -97,7 +97,7 @@ module Spree
def touch_users(user_ids)
return if user_ids.blank?
- Spree.user_class.where(id: user_ids).touch_all
+ Spree.customer_class.where(id: user_ids).touch_all
end
end
end
diff --git a/spree/core/app/models/spree/customer_group_user.rb b/spree/core/app/models/spree/customer_group_user.rb
index 330f7704b8..d25f62bfaf 100644
--- a/spree/core/app/models/spree/customer_group_user.rb
+++ b/spree/core/app/models/spree/customer_group_user.rb
@@ -4,13 +4,16 @@ module Spree
# Associations
#
belongs_to :customer_group, class_name: 'Spree::CustomerGroup'
- belongs_to :user, polymorphic: true
+ belongs_to :customer, polymorphic: true
+
+ include Spree::DeprecatedCustomerAlias
+ alias_attribute :user_type, :customer_type
#
# Validations
#
validates :customer_group, presence: true
- validates :user, presence: true
- validates :customer_group_id, uniqueness: { scope: [:user_id, :user_type] }
+ validates :customer, presence: true
+ validates :customer_group_id, uniqueness: { scope: [:customer_id, :customer_type] }
end
end
diff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rb
index 8aeac50436..e5b09da4b2 100644
--- a/spree/core/app/models/spree/export.rb
+++ b/spree/core/app/models/spree/export.rb
@@ -182,7 +182,7 @@ module Spree
# eg. Spree::Exports::Products => Spree::Product
def model_class
if type == 'Spree::Exports::Customers'
- Spree.user_class
+ Spree.customer_class
else
"Spree::#{type.demodulize.singularize}".constantize
end
diff --git a/spree/core/app/models/spree/gateway/custom_payment_source_method.rb b/spree/core/app/models/spree/gateway/custom_payment_source_method.rb
index ed647f5f5f..c548c31360 100644
--- a/spree/core/app/models/spree/gateway/custom_payment_source_method.rb
+++ b/spree/core/app/models/spree/gateway/custom_payment_source_method.rb
@@ -31,7 +31,7 @@ module Spree
# simulate a 3rd party payment gateway api to fetch/or create a customer
def find_or_create_customer(user)
- gateway_customers.find_or_create_by!(user: user, profile_id: "CUSTOMER-#{user.id}")
+ gateway_customers.find_or_create_by!(customer: user, profile_id: "CUSTOMER-#{user.id}")
end
end
end
diff --git a/spree/core/app/models/spree/gateway_customer.rb b/spree/core/app/models/spree/gateway_customer.rb
index f5d79b6c72..666285dd81 100644
--- a/spree/core/app/models/spree/gateway_customer.rb
+++ b/spree/core/app/models/spree/gateway_customer.rb
@@ -3,7 +3,8 @@ module Spree
has_prefix_id :gcus
belongs_to :payment_method, class_name: 'Spree::PaymentMethod'
- belongs_to :user, class_name: Spree.user_class.to_s
+ belongs_to :customer, class_name: Spree.customer_class.to_s
+ include Spree::DeprecatedCustomerAlias
validates :payment_method, presence: true
validates :user, presence: true
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index 1afee7da9f..6ece607b93 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -43,13 +43,14 @@ module Spree
# Associations
#
belongs_to :store, class_name: 'Spree::Store'
- belongs_to :user, class_name: Spree.user_class.to_s, optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
+ include Spree::DeprecatedCustomerAlias
belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
belongs_to :batch, class_name: 'Spree::GiftCardBatch', optional: true, foreign_key: :gift_card_batch_id
has_many :store_credits, class_name: 'Spree::StoreCredit', as: :originator
has_many :orders, inverse_of: :gift_card, class_name: 'Spree::Order'
- has_many :users, through: :orders, class_name: Spree.user_class.to_s
+ has_many :users, through: :orders, source: :customer
#
# Scopes
@@ -62,7 +63,7 @@ module Spree
#
# Ransack
#
- self.whitelisted_ransackable_attributes = %w[code user_id state gift_card_batch_id created_by_id]
+ self.whitelisted_ransackable_attributes = %w[code customer_id user_id state gift_card_batch_id created_by_id]
self.whitelisted_ransackable_associations = %w[users orders batch]
self.whitelisted_ransackable_scopes = %w[active expired redeemed partially_redeemed]
@@ -93,7 +94,7 @@ module Spree
amount - amount_used - amount_authorized
end
- delegate :email, to: :user, prefix: true, allow_nil: true
+ delegate :email, to: :customer, prefix: true, allow_nil: true
def self.json_api_columns
%w[code amount expires_at]
diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rb
index 0294802dc4..88ebb14b37 100644
--- a/spree/core/app/models/spree/import.rb
+++ b/spree/core/app/models/spree/import.rb
@@ -239,7 +239,7 @@ module Spree
# @return [Class]
def model_class
if type == 'Spree::Imports::Customers'
- Spree.user_class
+ Spree.customer_class
else
"Spree::#{type.demodulize.singularize}".safe_constantize
end
@@ -454,7 +454,7 @@ module Spree
# eg. Spree::Imports::Orders => Spree::Order
def model_class
- return Spree.user_class if to_s == 'Spree::Imports::Customers'
+ return Spree.customer_class if to_s == 'Spree::Imports::Customers'
klass = "Spree::#{to_s.demodulize.singularize}".safe_constantize
diff --git a/spree/core/app/models/spree/legacy_user.rb b/spree/core/app/models/spree/legacy_user.rb
index 850e8ff5b4..60eaa17cb7 100644
--- a/spree/core/app/models/spree/legacy_user.rb
+++ b/spree/core/app/models/spree/legacy_user.rb
@@ -5,7 +5,7 @@ module Spree
class LegacyUser < Spree.base_class
include Spree::UserAddress
include Spree::UserPaymentSource
- include Spree::UserMethods
+ include Spree::CustomerMethods
self.table_name = 'spree_users'
@@ -17,7 +17,7 @@ module Spree
before_save :encrypt_password, if: :password
# Simple password validation for testing purposes
- # In production, Spree.user_class should be overridden with a proper auth solution (e.g., Devise)
+ # In production, Spree.customer_class should be overridden with a proper auth solution (e.g., Devise)
def valid_password?(check_password)
return false if encrypted_password.blank?
diff --git a/spree/core/app/models/spree/newsletter_subscriber.rb b/spree/core/app/models/spree/newsletter_subscriber.rb
index cd0982586d..d5ec1633d1 100644
--- a/spree/core/app/models/spree/newsletter_subscriber.rb
+++ b/spree/core/app/models/spree/newsletter_subscriber.rb
@@ -16,9 +16,11 @@ module Spree
#
# Associations
#
- belongs_to :user, optional: true, class_name: Spree.user_class&.name
+ belongs_to :customer, optional: true, class_name: Spree.customer_class&.name
belongs_to :store, class_name: 'Spree::Store', required: true
+ include Spree::DeprecatedCustomerAlias
+
#
# Validations
#
@@ -46,7 +48,7 @@ module Spree
self.whitelisted_ransackable_scopes = %w[verified unverified]
def accepts_email_marketing
- return user.accepts_email_marketing if user.present?
+ return customer.accepts_email_marketing if customer.present?
verified?
end
@@ -59,12 +61,12 @@ module Spree
Spree::CSV::NewsletterSubscriberPresenter.new(self).call
end
- def self.subscribe(email:, user: nil, store: nil, redirect_url: nil)
+ def self.subscribe(email:, customer: nil, store: nil, redirect_url: nil)
store ||= Spree::Current.store
Spree::Newsletter::Subscribe.new(
email: email,
- current_user: user,
+ current_user: customer,
current_store: store,
redirect_url: redirect_url
).call
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 2d08a35a86..5e808c42da 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -112,7 +112,7 @@ module Spree
go_to_state :complete
end
- self.whitelisted_ransackable_associations = %w[shipments user created_by approver canceler promotions bill_address ship_address line_items store channel tags]
+ self.whitelisted_ransackable_associations = %w[shipments customer created_by approver canceler promotions bill_address ship_address line_items store channel tags]
self.whitelisted_ransackable_attributes = %w[
completed_at email number state status payment_state shipment_state
total item_total item_count considered_risky channel_id currency
@@ -143,12 +143,11 @@ module Spree
self.tag_list = tags
end
- ASSOCIATED_USER_ATTRIBUTES = [:user_id, :email, :bill_address_id, :ship_address_id]
+ ASSOCIATED_USER_ATTRIBUTES = [:customer_id, :email, :bill_address_id, :ship_address_id]
- # 6.0 forward-compat: User→Customer rename. Column stays user_id in 5.x.
- alias_attribute :customer_id, :user_id
+ include Spree::DeprecatedCustomerAlias
- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true, autosave: true
+ belongs_to :customer, class_name: "::#{Spree.customer_class}", optional: true, autosave: true
belongs_to :created_by, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :approver, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :canceler, class_name: "::#{Spree.admin_user_class}", optional: true
@@ -553,7 +552,7 @@ module Spree
# Associates the specified user with the order.
# Delegates to {Spree::Cart::Associate} service.
#
- # @param user [Spree.user_class] the user to associate with the order
+ # @param user [Spree.customer_class] the user to associate with the order
# @param override_email [Boolean] whether to override the order email with the user's email
# @return [Spree::ServiceModule::Result]
def associate_user!(user, override_email = true)
@@ -927,7 +926,7 @@ module Spree
# Cancels the order and records the canceler.
# Delegates to {Spree::Orders::Cancel} service.
#
- # @param user [Spree.user_class, nil] the user who canceled the order
+ # @param user [Spree.customer_class, nil] the user who canceled the order
# @param canceled_at [Time, nil] the time of cancellation (defaults to current time)
# @return [Spree::ServiceModule::Result]
def canceled_by(user, canceled_at = nil)
@@ -937,7 +936,7 @@ module Spree
# Approves the order and records the approver.
# Delegates to {Spree::Orders::Approve} service.
#
- # @param user [Spree.user_class, nil] the user who approved the order
+ # @param user [Spree.customer_class, nil] the user who approved the order
# @return [Spree::ServiceModule::Result]
def approved_by(user = nil)
Spree.order_approve_service.call(order: self, approver: user)
diff --git a/spree/core/app/models/spree/order/checkout.rb b/spree/core/app/models/spree/order/checkout.rb
index 276763ef00..904e80947c 100644
--- a/spree/core/app/models/spree/order/checkout.rb
+++ b/spree/core/app/models/spree/order/checkout.rb
@@ -135,7 +135,7 @@ module Spree
def subscribe_to_newsletter
return unless accept_marketing?
- Spree::NewsletterSubscriber.subscribe(email: email, user: user, store: store)
+ Spree::NewsletterSubscriber.subscribe(email: email, customer: customer, store: store)
end
def self.go_to_state(name, options = {})
diff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rb
index d6f52b7312..cd73f157c8 100644
--- a/spree/core/app/models/spree/payment_session.rb
+++ b/spree/core/app/models/spree/payment_session.rb
@@ -12,7 +12,7 @@ module Spree
belongs_to :order, class_name: 'Spree::Order'
belongs_to :payment_method, class_name: 'Spree::PaymentMethod'
- belongs_to :customer, class_name: Spree.user_class.to_s, optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
has_one :payment, class_name: 'Spree::Payment',
foreign_key: :response_code,
diff --git a/spree/core/app/models/spree/payment_setup_session.rb b/spree/core/app/models/spree/payment_setup_session.rb
index 9b2f333405..33ac8de864 100644
--- a/spree/core/app/models/spree/payment_setup_session.rb
+++ b/spree/core/app/models/spree/payment_setup_session.rb
@@ -10,7 +10,7 @@ module Spree
publishes_lifecycle_events
- belongs_to :customer, class_name: Spree.user_class.to_s, optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
belongs_to :payment_method, class_name: 'Spree::PaymentMethod'
belongs_to :payment_source, polymorphic: true, optional: true
diff --git a/spree/core/app/models/spree/payment_source.rb b/spree/core/app/models/spree/payment_source.rb
index 0860acbcfe..4e468e5a9b 100644
--- a/spree/core/app/models/spree/payment_source.rb
+++ b/spree/core/app/models/spree/payment_source.rb
@@ -11,7 +11,8 @@ module Spree
# Associations
#
belongs_to :payment_method, class_name: 'Spree::PaymentMethod'
- belongs_to :user, class_name: Spree.user_class.to_s, optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
+ include Spree::DeprecatedCustomerAlias
#
# Validations
@@ -26,9 +27,9 @@ module Spree
# Returns the gateway customer for the user.
# @return [Spree::GatewayCustomer]
def gateway_customer
- return if user.blank?
+ return if customer.blank?
- payment_method.gateway_customers.find_by(user: user)
+ payment_method.gateway_customers.find_by(customer: customer)
end
end
end
diff --git a/spree/core/app/models/spree/permission_sets/default_customer.rb b/spree/core/app/models/spree/permission_sets/default_customer.rb
index 5cbabd4f8b..40715ad1a2 100644
--- a/spree/core/app/models/spree/permission_sets/default_customer.rb
+++ b/spree/core/app/models/spree/permission_sets/default_customer.rb
@@ -47,8 +47,8 @@ module Spree
end
# User account management - available to all users (including guests for their own record)
- can :create, Spree.user_class
- can [:show, :update, :destroy], Spree.user_class, id: user.id
+ can :create, Spree.customer_class
+ can [:show, :update, :destroy], Spree.customer_class, id: user.id
# Address management - only for persisted users with matching user_id
can :manage, Spree::Address, user_id: user.id if user.persisted?
diff --git a/spree/core/app/models/spree/permission_sets/user_display.rb b/spree/core/app/models/spree/permission_sets/user_display.rb
index 1aa3911e25..dc376642b5 100644
--- a/spree/core/app/models/spree/permission_sets/user_display.rb
+++ b/spree/core/app/models/spree/permission_sets/user_display.rb
@@ -10,7 +10,7 @@ module Spree
module PermissionSets
class UserDisplay < Base
def activate!
- can [:read, :admin, :index], Spree.user_class
+ can [:read, :admin, :index], Spree.customer_class
can [:read, :admin], Spree::Address
can [:read, :admin], Spree::CreditCard
end
diff --git a/spree/core/app/models/spree/permission_sets/user_management.rb b/spree/core/app/models/spree/permission_sets/user_management.rb
index f59df27d78..b96f600417 100644
--- a/spree/core/app/models/spree/permission_sets/user_management.rb
+++ b/spree/core/app/models/spree/permission_sets/user_management.rb
@@ -10,7 +10,7 @@ module Spree
module PermissionSets
class UserManagement < Base
def activate!
- can :manage, Spree.user_class
+ can :manage, Spree.customer_class
can :manage, Spree::Address
can :manage, Spree::CreditCard
can [:read, :admin], Spree::Metafield
diff --git a/spree/core/app/models/spree/price_rules/user_rule.rb b/spree/core/app/models/spree/price_rules/user_rule.rb
index 72953c17b9..26020092cc 100644
--- a/spree/core/app/models/spree/price_rules/user_rule.rb
+++ b/spree/core/app/models/spree/price_rules/user_rule.rb
@@ -3,16 +3,16 @@ module Spree
class UserRule < Spree::PriceRule
# Stored as raw IDs. Accepts prefixed IDs (the user class's prefix,
# e.g. `usr_…`) from API callers and decodes them on write. Resolves
- # `Spree.user_class` lazily — the user class is configured at boot,
+ # `Spree.customer_class` lazily — the user class is configured at boot,
# and class-body evaluation runs before that on cold loads.
preference :user_ids, :array, default: [], parse_on_set: ->(values) {
- normalize_id_preference(klass: Spree.user_class).call(values)
+ normalize_id_preference(klass: Spree.customer_class).call(values)
}
def users
return [] if preferred_user_ids.blank?
- Spree.user_class.where(id: preferred_user_ids)
+ Spree.customer_class.where(id: preferred_user_ids)
end
def applicable?(context)
diff --git a/spree/core/app/models/spree/promotion/rules/user.rb b/spree/core/app/models/spree/promotion/rules/user.rb
index 87e569d349..0e8133b9f2 100644
--- a/spree/core/app/models/spree/promotion/rules/user.rb
+++ b/spree/core/app/models/spree/promotion/rules/user.rb
@@ -8,7 +8,7 @@ module Spree
has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser',
foreign_key: :promotion_rule_id,
dependent: :destroy
- has_many :users, through: :promotion_rule_users, class_name: "::#{Spree.user_class}"
+ has_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);
@@ -46,7 +46,7 @@ module Spree
end
def eligible_user_ids
- @eligible_user_ids ||= promotion_rule_users.pluck(:user_id)
+ @eligible_user_ids ||= promotion_rule_users.pluck(:customer_id)
end
def eligible?(order, _options = {})
diff --git a/spree/core/app/models/spree/promotion_rule_user.rb b/spree/core/app/models/spree/promotion_rule_user.rb
index 9bb8bf9d5b..6bfc3939e5 100644
--- a/spree/core/app/models/spree/promotion_rule_user.rb
+++ b/spree/core/app/models/spree/promotion_rule_user.rb
@@ -1,7 +1,8 @@
module Spree
class PromotionRuleUser < Spree.base_class
belongs_to :promotion_rule, class_name: 'Spree::PromotionRule'
- belongs_to :user, class_name: "::#{Spree.user_class}"
+ belongs_to :customer, class_name: "::#{Spree.customer_class}"
+ include Spree::DeprecatedCustomerAlias
validates :user, :promotion_rule, presence: true
validates :user_id, uniqueness: { scope: :promotion_rule_id }, allow_nil: true
diff --git a/spree/core/app/models/spree/role.rb b/spree/core/app/models/spree/role.rb
index 21c7d2b728..a413ec2532 100644
--- a/spree/core/app/models/spree/role.rb
+++ b/spree/core/app/models/spree/role.rb
@@ -10,7 +10,7 @@ module Spree
# Associations
#
has_many :role_users, class_name: 'Spree::RoleUser', dependent: :destroy
- has_many :users, through: :role_users, source: :user, source_type: Spree.user_class.to_s
+ has_many :users, through: :role_users, source: :user, source_type: Spree.customer_class.to_s
has_many :admin_users, through: :role_users, source: :user, source_type: Spree.admin_user_class.to_s
has_many :invitations, class_name: 'Spree::Invitation', dependent: :destroy
diff --git a/spree/core/app/models/spree/state_change.rb b/spree/core/app/models/spree/state_change.rb
index a73f831308..71869dda72 100644
--- a/spree/core/app/models/spree/state_change.rb
+++ b/spree/core/app/models/spree/state_change.rb
@@ -2,7 +2,7 @@ module Spree
class StateChange < Spree.base_class
has_prefix_id :sc
- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true
+ belongs_to :user, class_name: "::#{Spree.customer_class}", optional: true
belongs_to :stateful, polymorphic: true
def <=>(other)
diff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rb
index adbce9e7d9..214681c87e 100644
--- a/spree/core/app/models/spree/store_credit.rb
+++ b/spree/core/app/models/spree/store_credit.rb
@@ -19,7 +19,8 @@ module Spree
ALLOCATION_ACTION = 'allocation'.freeze
belongs_to :store, class_name: 'Spree::Store'
- belongs_to :user, class_name: "::#{Spree.user_class}", foreign_key: 'user_id'
+ belongs_to :customer, class_name: "::#{Spree.customer_class}"
+ include Spree::DeprecatedCustomerAlias
belongs_to :category, class_name: 'Spree::StoreCreditCategory', optional: true
belongs_to :created_by, class_name: Spree.admin_user_class.to_s, foreign_key: 'created_by_id', optional: true
belongs_to :credit_type, class_name: 'Spree::StoreCreditType', foreign_key: 'type_id', optional: true
@@ -58,8 +59,8 @@ module Spree
self[:amount] = Spree::LocalizedNumber.parse(amount)
end
- self.whitelisted_ransackable_attributes = %w[user_id created_by_id amount currency type_id]
- self.whitelisted_ransackable_associations = %w[type user created_by]
+ self.whitelisted_ransackable_attributes = %w[customer_id user_id created_by_id amount currency type_id]
+ self.whitelisted_ransackable_associations = %w[type customer created_by]
def amount_remaining
amount - amount_used - amount_authorized
diff --git a/spree/core/app/models/spree/user_identity.rb b/spree/core/app/models/spree/user_identity.rb
index 31a6aa375c..a68183280c 100644
--- a/spree/core/app/models/spree/user_identity.rb
+++ b/spree/core/app/models/spree/user_identity.rb
@@ -21,7 +21,7 @@ module Spree
# Find or create user from OAuth data
def self.find_or_create_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)
- user_class ||= Spree.user_class
+ user_class ||= Spree.customer_class
user_type = user_class.name
identity = find_by(provider: provider, uid: uid, user_type: user_type)
@@ -57,7 +57,7 @@ module Spree
end
def self.create_user_from_oauth(provider:, uid:, info:, tokens: {}, user_class: nil)
- user_class ||= Spree.user_class
+ user_class ||= Spree.customer_class
transaction do
user = user_class.create!(
diff --git a/spree/core/app/models/spree/wishlist.rb b/spree/core/app/models/spree/wishlist.rb
index 8bf0241c01..b158302d2b 100644
--- a/spree/core/app/models/spree/wishlist.rb
+++ b/spree/core/app/models/spree/wishlist.rb
@@ -12,7 +12,8 @@ module Spree
has_secure_token
end
- belongs_to :user, class_name: "::#{Spree.user_class}", touch: true
+ belongs_to :customer, class_name: "::#{Spree.customer_class}", touch: true
+ include Spree::DeprecatedCustomerAlias
belongs_to :store, class_name: 'Spree::Store'
has_many :wished_items, class_name: 'Spree::WishedItem', dependent: :destroy
diff --git a/spree/core/app/services/spree/account/create.rb b/spree/core/app/services/spree/account/create.rb
index 674c4834f5..a5193f6b2d 100644
--- a/spree/core/app/services/spree/account/create.rb
+++ b/spree/core/app/services/spree/account/create.rb
@@ -4,7 +4,7 @@ module Spree
prepend Spree::ServiceModule::Base
def call(user_params: {})
- user = Spree.user_class.new(user_params)
+ user = Spree.customer_class.new(user_params)
if user.save
success(user)
diff --git a/spree/core/app/services/spree/imports/row_processors/customer.rb b/spree/core/app/services/spree/imports/row_processors/customer.rb
index 48ae2fee0d..83c50d7819 100644
--- a/spree/core/app/services/spree/imports/row_processors/customer.rb
+++ b/spree/core/app/services/spree/imports/row_processors/customer.rb
@@ -16,7 +16,7 @@ module Spree
email = attributes['email'].to_s.strip.downcase
raise ArgumentError, 'Email is required' if email.blank?
- Spree.user_class.find_or_initialize_by(email: email)
+ Spree.customer_class.find_or_initialize_by(email: email)
end
def assign_user_attributes(user)
diff --git a/spree/core/app/services/spree/newsletter/subscribe.rb b/spree/core/app/services/spree/newsletter/subscribe.rb
index b425237321..f4ea0b0b7f 100644
--- a/spree/core/app/services/spree/newsletter/subscribe.rb
+++ b/spree/core/app/services/spree/newsletter/subscribe.rb
@@ -59,7 +59,7 @@ module Spree
end
def known_user
- @known_user ||= current_user || Spree.user_class.find_by(email: email)
+ @known_user ||= current_user || Spree.customer_class.find_by(email: email)
end
end
end
diff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rb
index f64b621809..f4074b9496 100644
--- a/spree/core/app/services/spree/orders/create.rb
+++ b/spree/core/app/services/spree/orders/create.rb
@@ -14,7 +14,7 @@ module Spree
attr_reader :discount_application_errors
# @param store [Spree::Store]
- # @param user [Object, nil] resolved customer (Spree.user_class instance)
+ # @param user [Object, nil] resolved customer (Spree.customer_class instance)
# @param params [Hash] order params (see admin API docs)
# @return [Spree::ServiceModule::Result]
def call(store:, user: nil, params: {})
diff --git a/spree/core/app/services/spree/orders/create_user_account.rb b/spree/core/app/services/spree/orders/create_user_account.rb
index af49acfe35..0472a40232 100644
--- a/spree/core/app/services/spree/orders/create_user_account.rb
+++ b/spree/core/app/services/spree/orders/create_user_account.rb
@@ -6,10 +6,10 @@ module Spree
prepend ::Spree::ServiceModule::Base
def call(order:, accepts_email_marketing: false)
- existing_user = Spree.user_class.find_by(email: order.email)
+ existing_user = Spree.customer_class.find_by(email: order.email)
if existing_user.present?
- order.update_columns(user_id: existing_user.id, updated_at: Time.current)
- order.user = existing_user
+ order.update_columns(customer_id: existing_user.id, updated_at: Time.current)
+ order.customer = existing_user
return success(existing_user)
end
@@ -21,8 +21,8 @@ module Spree
# assign newly created user to the order
# using update_columns to avoid running validations/callbacks
- order.update_columns(user_id: user.id, updated_at: Time.current)
- order.user = user
+ order.update_columns(customer_id: user.id, updated_at: Time.current)
+ order.customer = user
# send welcome email
user.send_welcome_email if user.respond_to?(:send_welcome_email)
@@ -40,7 +40,7 @@ module Spree
# we need to generate a password for the user
password = SecureRandom.base58(16)
- user = Spree.user_class.new
+ user = Spree.customer_class.new
user.email = order.email
user.first_name = firstname if user.respond_to?(:first_name)
user.last_name = lastname if user.respond_to?(:last_name)
@@ -56,7 +56,7 @@ module Spree
def assign_bill_address(order, user)
if order.bill_address.present?
- order.bill_address.update_columns(user_id: user.id, updated_at: Time.current)
+ order.bill_address.update_columns(customer_id: user.id, updated_at: Time.current)
user.update_columns(bill_address_id: order.bill_address_id, updated_at: Time.current) unless user.bill_address_id.present?
end
@@ -64,7 +64,7 @@ module Spree
def assign_ship_address(order, user)
if order.ship_address.present?
- order.ship_address.update_columns(user_id: user.id, updated_at: Time.current)
+ order.ship_address.update_columns(customer_id: user.id, updated_at: Time.current)
user.update_columns(ship_address_id: order.ship_address_id, updated_at: Time.current) unless user.ship_address_id.present?
end
diff --git a/spree/core/app/services/spree/payments/create.rb b/spree/core/app/services/spree/payments/create.rb
index 75c38c7ebd..ccb1a9e655 100644
--- a/spree/core/app/services/spree/payments/create.rb
+++ b/spree/core/app/services/spree/payments/create.rb
@@ -31,7 +31,7 @@ module Spree
if payment_method&.source_required?
if order.user.present? && params[:source_id].present?
- source = payment_method.payment_source_class.find_by(id: params[:source_id], user: order.user)
+ source = payment_method.payment_source_class.find_by(id: params[:source_id], customer: order.customer)
return failure(nil, :source_not_found) if source.nil?
else
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 929c6b55ea..9a83d76246 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -289,6 +289,14 @@ en:
content_type: has not allowed content type
type:
inclusion: is not included in the list of allowed types
+ spree/customer:
+ attributes:
+ bill_address_id:
+ belongs_to_other_user: belongs to other user
+ deprecated_in_completed_order: deprecated in completed order
+ ship_address_id:
+ belongs_to_other_user: belongs to other user
+ deprecated_in_completed_order: deprecated in completed order
spree/legacy_user:
attributes:
bill_address_id:
diff --git a/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb b/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb
index c0a439e278..e42eb27684 100644
--- a/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb
+++ b/spree/core/lib/generators/spree/authentication/custom/custom_generator.rb
@@ -22,14 +22,14 @@ module Spree
end\n}
end
- user_class_file = Rails.root.join('app', 'models', "#{Spree.user_class.name.underscore}.rb")
+ user_class_file = Rails.root.join('app', 'models', "#{Spree.customer_class.name.underscore}.rb")
if File.exist?(user_class_file)
- inject_into_file user_class_file, after: "class #{Spree.user_class.name} < ApplicationRecord\n" do
+ inject_into_file user_class_file, after: "class #{Spree.customer_class.name} < ApplicationRecord\n" do
<<-RUBY
# Spree modules
include Spree::UserAddress
- include Spree::UserMethods
+ include Spree::CustomerMethods
include Spree::UserPaymentSource
RUBY
end
@@ -39,7 +39,7 @@ module Spree
say <<~RUBY
# Spree modules
include Spree::UserAddress
- include Spree::UserMethods
+ include Spree::CustomerMethods
include Spree::UserPaymentSource
RUBY
end
diff --git a/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb b/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb
index 4a05c50f9e..e3bef17fa6 100644
--- a/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb
+++ b/spree/core/lib/generators/spree/authentication/devise/devise_generator.rb
@@ -22,14 +22,14 @@ module Spree
end\n}
end
- user_class_file = Rails.root.join('app', 'models', "#{Spree.user_class.name.underscore}.rb")
+ user_class_file = Rails.root.join('app', 'models', "#{Spree.customer_class.name.underscore}.rb")
if File.exist?(user_class_file)
- inject_into_file user_class_file, after: "class #{Spree.user_class.name} < ApplicationRecord\n" do
+ inject_into_file user_class_file, after: "class #{Spree.customer_class.name} < ApplicationRecord\n" do
<<-RUBY
# Spree modules
include Spree::UserAddress
- include Spree::UserMethods
+ include Spree::CustomerMethods
include Spree::UserPaymentSource
RUBY
end
@@ -41,14 +41,14 @@ module Spree
say <<~RUBY
# Spree modules
include Spree::UserAddress
- include Spree::UserMethods
+ include Spree::CustomerMethods
include Spree::UserPaymentSource
RUBY
say "Please replace < ApplicationRecord with < Spree.base_class in #{user_class_file}"
end
- if Spree.admin_user_class != Spree.user_class
+ if Spree.admin_user_class != Spree.customer_class
admin_user_class_file = Rails.root.join('app', 'models', "#{Spree.admin_user_class.name.underscore}.rb")
if File.exist?(admin_user_class_file)
diff --git a/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt b/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt
index 331cb30d22..75a3d06e96 100644
--- a/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt
+++ b/spree/core/lib/generators/spree/authentication/devise/templates/authentication_helpers.rb.tt
@@ -14,27 +14,27 @@ module Spree
end
def spree_current_user
- send("current_#{Spree.user_class.model_name.singular_route_key}")
+ send("current_#{Spree.customer_class.model_name.singular_route_key}")
end
def spree_login_path(opts = {})
- new_session_path(Spree.user_class.model_name.singular_route_key, opts)
+ new_session_path(Spree.customer_class.model_name.singular_route_key, opts)
end
def spree_signup_path(opts = {})
- new_registration_path(Spree.user_class.model_name.singular_route_key, opts)
+ new_registration_path(Spree.customer_class.model_name.singular_route_key, opts)
end
def spree_logout_path(opts = {})
- destroy_session_path(Spree.user_class.model_name.singular_route_key, opts)
+ destroy_session_path(Spree.customer_class.model_name.singular_route_key, opts)
end
def spree_forgot_password_path(opts = {})
- new_password_path(Spree.user_class.model_name.singular_route_key, opts)
+ new_password_path(Spree.customer_class.model_name.singular_route_key, opts)
end
def spree_edit_password_path(opts = {})
- edit_registration_path(Spree.user_class.model_name.singular_route_key, opts)
+ edit_registration_path(Spree.customer_class.model_name.singular_route_key, opts)
end
def spree_admin_login_path(opts = {})
diff --git a/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt b/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt
index 64811a48df..f628d84cb2 100644
--- a/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt
+++ b/spree/core/lib/generators/spree/authentication/dummy/templates/create_spree_admin_users.rb.tt
@@ -2,6 +2,7 @@ class CreateSpreeAdminUsers < ActiveRecord::Migration<%= migration_version %>
def change
create_table :spree_admin_users do |t|
t.string :encrypted_password, limit: 128
+ t.string :password_digest
t.string :email
t.string :remember_token
t.string :persistence_token
diff --git a/spree/core/lib/generators/spree/model/model_generator.rb b/spree/core/lib/generators/spree/model/model_generator.rb
index 2021c7a2cb..b12198e411 100644
--- a/spree/core/lib/generators/spree/model/model_generator.rb
+++ b/spree/core/lib/generators/spree/model/model_generator.rb
@@ -52,7 +52,7 @@ module Spree
"spree_#{super.delete_prefix('spree_')}"
end
- # Resolution: explicit class hint in attribute spec → Spree.user_class
+ # Resolution: explicit class hint in attribute spec → Spree.customer_class
# for user-named columns → Spree.admin_user_class for admin-user-named
# columns → Spree::<CamelCasedName> default. The Rails attribute parser
# splits on `:` so explicit hints can only be unqualified names; users
@@ -63,7 +63,7 @@ module Spree
case attribute.name
when 'user', 'user_id'
- '"::#{Spree.user_class}"'
+ '"::#{Spree.customer_class}"'
when 'admin_user', 'admin_user_id', 'created_by', 'created_by_id',
'approver', 'approver_id', 'canceler', 'canceler_id'
'"::#{Spree.admin_user_class}"'
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index edd223b31a..8296caa59e 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -39,7 +39,7 @@ require 'sqids'
StateMachines::Machine.ignore_method_conflicts = true
module Spree
- mattr_accessor :base_class, :user_class, :admin_user_class,
+ mattr_accessor :base_class, :customer_class, :admin_user_class,
:private_storage_service_name, :public_storage_service_name,
:cdn_host, :root_domain, :searcher_class, :events_adapter_class, :queues,
:google_places_api_key
@@ -53,14 +53,26 @@ module Spree
end
end
- def self.user_class(constantize: true)
- if @@user_class.is_a?(Class)
- raise 'Spree.user_class MUST be a String or Symbol object, not a Class object.'
- elsif @@user_class.is_a?(String) || @@user_class.is_a?(Symbol)
- constantize ? @@user_class.to_s.constantize : @@user_class.to_s
+ def self.customer_class(constantize: true)
+ if @@customer_class.is_a?(Class)
+ raise 'Spree.customer_class MUST be a String or Symbol object, not a Class object.'
+ elsif @@customer_class.is_a?(String) || @@customer_class.is_a?(Symbol)
+ constantize ? @@customer_class.to_s.constantize : @@customer_class.to_s
end
end
+ # @deprecated Spree.user_class was renamed to Spree.customer_class in 6.0; removed in 6.1.
+ def self.user_class(constantize: true)
+ Spree::Deprecation.warn('Spree.user_class is deprecated and will be removed in Spree 6.1. Use Spree.customer_class instead.') if defined?(Spree::Deprecation)
+ customer_class(constantize: constantize)
+ end
+
+ # @deprecated Spree.user_class= was renamed to Spree.customer_class= in 6.0; removed in 6.1.
+ def self.user_class=(value)
+ Spree::Deprecation.warn('Spree.user_class= is deprecated and will be removed in Spree 6.1. Use Spree.customer_class= instead.') if defined?(Spree::Deprecation)
+ self.customer_class = value
+ end
+
def self.admin_user_class(constantize: true)
if @@admin_user_class.is_a?(Class)
raise 'Spree.admin_user_class MUST be a String or Symbol object, not a Class object.'
diff --git a/spree/core/lib/spree/core/controller_helpers/auth.rb b/spree/core/lib/spree/core/controller_helpers/auth.rb
index 611efe4c7b..08e1b28315 100644
--- a/spree/core/lib/spree/core/controller_helpers/auth.rb
+++ b/spree/core/lib/spree/core/controller_helpers/auth.rb
@@ -31,7 +31,7 @@ module Spree
end
def store_location_session_key
- "#{Spree.user_class.model_name.singular_route_key.to_sym}_return_to"
+ "#{Spree.customer_class.model_name.singular_route_key.to_sym}_return_to"
end
# proxy method to *possible* spree_current_user method
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 845abf8e9d..451d520b6d 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -132,8 +132,8 @@ module Spree
end
# Promotion rules need to be evaluated on after initialize otherwise
- # Spree.user_class would be nil and users might experience errors related
- # to malformed model associations (Spree.user_class is only defined on
+ # Spree.customer_class would be nil and users might experience errors related
+ # to malformed model associations (Spree.customer_class is only defined on
# the app initializer)
config.after_initialize do
Rails.application.config.spree.calculators.shipping_methods = [
@@ -302,7 +302,7 @@ module Spree
Rails.application.config.spree.taggable_types = [
'Spree::Product',
'Spree::Order',
- Spree.user_class.to_s
+ Spree.customer_class.to_s
]
Rails.application.config.spree.metafields.types = [
@@ -343,7 +343,7 @@ module Spree
Spree::Category,
Spree::Taxonomy,
Spree::Variant,
- Spree.user_class
+ Spree.customer_class
]
Rails.application.config.spree.analytics_events = {
diff --git a/spree/core/lib/spree/core/previews/preview_data.rb b/spree/core/lib/spree/core/previews/preview_data.rb
index 41cce0aff7..936d65d85a 100644
--- a/spree/core/lib/spree/core/previews/preview_data.rb
+++ b/spree/core/lib/spree/core/previews/preview_data.rb
@@ -25,8 +25,8 @@ module Spree
# A customer for previews of customer-facing account emails. Falls back to
# an unsaved instance when the database has no users.
def customer
- Spree.user_class.first ||
- Spree.user_class.new(email: '[email protected]').tap do |user|
+ Spree.customer_class.first ||
+ Spree.customer_class.new(email: '[email protected]').tap do |user|
user.first_name = 'Alex' if user.respond_to?(:first_name=)
end
end
diff --git a/spree/core/lib/tasks/core.rake b/spree/core/lib/tasks/core.rake
index 14807d1da0..01020b3941 100644
--- a/spree/core/lib/tasks/core.rake
+++ b/spree/core/lib/tasks/core.rake
@@ -36,7 +36,7 @@ namespace :core do
desc 'Migrate newsletter subscribers'
task migrate_newsletter_subscribers: :environment do |_t, _args|
- Spree.user_class.where(accepts_email_marketing: true).in_batches(of: 500) do |user_batch|
+ Spree.customer_class.where(accepts_email_marketing: true).in_batches(of: 500) do |user_batch|
subscriber_attributes = user_batch.pluck(:id, :email, :updated_at).map do |id, email, updated_at|
{
email: Spree::NewsletterSubscriber.new(email: email).email, # normalized email
diff --git a/spree/emails/app/subscribers/spree/customer_email_subscriber.rb b/spree/emails/app/subscribers/spree/customer_email_subscriber.rb
index ba51f24677..e64c05de4e 100644
--- a/spree/emails/app/subscribers/spree/customer_email_subscriber.rb
+++ b/spree/emails/app/subscribers/spree/customer_email_subscriber.rb
@@ -5,7 +5,7 @@ module Spree
subscribes_to 'customer.password_reset_requested'
def handle(event)
- user = Spree.user_class.find_by(email: event.payload['email'])
+ user = Spree.customer_class.find_by(email: event.payload['email'])
return unless user
store = find_store(event)
diff --git a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
index 18a9e935f8..b2bb3cfb41 100644
--- a/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
+++ b/spree/lib/generators/spree/install/templates/config/initializers/spree.rb
@@ -133,5 +133,5 @@ end
# Search provider
# Spree.search_provider = 'Spree::SearchProvider::Meilisearch'
-Spree.user_class = <%= (options[:user_class].blank? ? 'Spree::LegacyUser' : options[:user_class]).inspect %>
-Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::LegacyAdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>
+Spree.customer_class = <%= (options[:user_class].blank? ? 'Spree::Customer' : options[:user_class]).inspect %>
+Spree.admin_user_class = <%= (options[:admin_user_class].blank? ? (options[:user_class].blank? ? 'Spree::AdminUser' : options[:user_class]) : options[:admin_user_class]).inspect %>