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.

43.1 KB
Raw Blame

Platform-Owned Authentication & User Model Rename

Status: In Progress (RefreshToken shipped in 5.4 ✓; Phases 1–3 implemented — gem-owned Spree::Customer/Spree::AdminUser models + Spree.customer_class rename + user_id→customer_id (fresh-install migration ordering corrected — two redundant spree_admin_users ALTER migrations dropped); Phase 2 data migration implemented — spree:upgrade:migrate_users_to_customers (Path A) + custom-model recipe (Path B); Phase 4 mostly shipped earlier (refresh tokens + endpoints + rate limiting), with account-lockout enforcement + config prefs + admin-logout throttle landed; Phase 5 (Devise + legacy models removed, core/api-scoped; headless gem-owned template.rb) + Phase 6 (aliases kept, Devise docs swept) done; spree/admin removal, starter 5b, the 6.0 upgrade guide, and spree_users teardown deferred. Two 6.0 items still open (2026-08-03): password-length policy — there is currently no minimum at all (Phase 4) — and Phase 7, SSO/OIDC login in the React dashboard) 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-08-03

Summary

Two changes in one plan:

  1. Drop Devise, own the auth stack. Spree already has a JWT-based, strategy-pattern auth system that's fully independent of Devise for the API layer. Devise is only used by the deprecated Rails admin (being replaced by React SPA in 6.0). Remove the Devise dependency entirely and make Spree's built-in auth the default — has_secure_password, JWT tokens, pluggable strategies.

  2. Rename User → Customer. Spree.user_class → Spree.customer_class. Default customer model becomes Spree::Customer (replaces Spree::LegacyUser). Spree.admin_user_class stays, default becomes Spree::AdminUser (replaces Spree::LegacyAdminUser). "User" is ambiguous — "customer" is what storefront users actually are.

Problem

Devise dependency

  1. Wrong tool for headless. Devise is a full-stack Rails auth library — controllers, views, routes, Warden middleware, cookie sessions. Spree is API-first with JWT tokens. Devise provides ~5% of its surface area to Spree (password hashing, reset tokens), the rest is dead weight.

  2. Sends the wrong signal. TypeScript developers evaluating Spree see Devise in the dependency chain and think "this is a Rails monolith." Removing it strengthens the API-first positioning.

  3. Already built. The core auth stack is already implemented and operational:

    • Spree::Authentication::Strategies::BaseStrategy — pluggable strategy pattern
    • Spree::Authentication::Strategies::EmailPasswordStrategy — email+password with bcrypt
    • Spree::UserIdentity — OAuth/social login identity storage
    • JWT issuance and validation in API v3 controllers
    • API key system (publishable pk_* + secret sk_*)
    • Password reset via generates_token_for (Rails 7.1+)
  4. Conditional dependency anyway. Devise is not in any gemspec — it's already optional via conditional inheritance in the legacy admin controllers (defined?(Devise::SessionsController) ? Devise::SessionsController : ...). The legacy Rails admin is being replaced by the React SPA.

User naming

  1. "User" is ambiguous. Spree.user_class could mean customer, admin, API consumer, or anyone. Every new developer asks "which user?" The model is Spree::LegacyUser — the name itself admits the problem.

  2. API already uses "customer." Store API endpoints are /store/customers, /store/customer, the serializer is CustomerSerializer. But the model is Spree.user_class. This mismatch confuses developers.

Current State

Auth system

Component Status Location
JWT issuance/validation Built api/controllers/concerns/spree/api/v3/jwt_authentication.rb
API key auth (pk/sk) Built api/controllers/concerns/spree/api/v3/api_key_authentication.rb
Strategy framework Built core/app/models/spree/authentication/strategies/base_strategy.rb
Email+password strategy Built core/app/models/spree/authentication/strategies/email_password_strategy.rb
OAuth identity storage Built core/app/models/spree/user_identity.rb
Password reset tokens Built core/app/models/concerns/spree/user_methods.rb (via generates_token_for)
Store API auth endpoints Built api/controllers/spree/api/v3/store/auth_controller.rb
Rate limiting Available Rails 7.1+ rate_limit DSL
Devise (legacy admin only) Conditional admin/app/controllers/spree/admin/user_sessions_controller.rb

User models

Current Purpose Default class
Spree.user_class Storefront customer Spree::LegacyUser
Spree.admin_user_class Admin/staff user Spree::LegacyAdminUser

Key Decisions (do not deviate without discussion)

Auth

  • Drop Devise entirely. No conditional fallbacks, no generator, no devise_for routes. The legacy Rails admin is gone in 6.0 (replaced by React SPA).
  • has_secure_password is the foundation. Rails core, no gem dependency. Handles bcrypt hashing, authenticate(password) method, password confirmation validation.
  • JWT stays as-is. Short-lived access tokens, separate audiences for store (store_api) and admin (admin_api). Already implemented and working.
  • Strategy pattern stays as-is. Spree.store_authentication_strategies and Spree.admin_authentication_strategies for registering custom providers.
  • Add refresh token support (5.4). Short-lived access JWT (15 min) + long-lived refresh token (stored in DB, rotatable, revocable). Better UX for React admin and Next.js storefront — silent refresh instead of forced re-login. Ships in 5.4 — can't wait for 6.0 because every storefront has broken session management without it.
  • Rate limiting on auth endpoints. Use Rails rate_limit DSL on login, register, and password reset endpoints. Baked in, not optional.
  • Account lockout after failed attempts. Track failed_attempts and locked_at on Customer/AdminUser model. Simple, no Devise dependency.
  • Default models ship in the gem — the host app owns no auth code (2026-07-28). Spree::Customer and Spree::AdminUser live in spree_core like any other Spree model (Product, Order). The only historic reason for a host-app-owned user model was Devise — devise_for routes and the devise :... declaration require an app-local class; dropping Devise removes that constraint. Gem-owned models mean every auth improvement (lockout tuning, rate limiting, MFA/passkeys, token hardening) arrives via a normal gem upgrade + migration instead of a changelog entry asking users to hand-edit scaffolded code. This matches the broader 6.0 strategy: customization via configuration and existing extension systems, not Rails code in the host app. Apps needing extra customer columns add their own migrations against spree_customers or use metafields.
  • No authentication generators at all. Remove both spree/authentication/devise/ and spree/authentication/custom/ generator directories. The inject_into_file scaffolding is fragile (silently degrades to "add these lines manually" when the class definition doesn't match its anchor) and produces code frozen at generation time. Custom user classes remain fully supported — Spree.customer_class = 'MyApp::User' + one concern include — as a documented recipe, not generated code.
  • Keep the adapter pattern. Spree.store_authentication_strategies lets developers plug in Auth0, Clerk, Firebase, LDAP, etc. by implementing BaseStrategy.
  • The credential stays on the user model — no separate credential table (2026-08-03). password_digest lives on spree_customers / spree_admin_users, not on Spree::UserIdentity. Surveyed platforms are split: Vendure keeps passwordHash on a NativeAuthenticationMethod row (STI alongside ExternalAuthenticationMethod), Medusa v2 keeps it in provider_identity.provider_metadata, and Saleor keeps it on the User row (inherited from Django's AbstractBaseUser). Vendure and Medusa gain two things from the split: several credentials of the same kind per user, and a clean "this account has no password" state. Spree already has the second — password_digest is nullable, has_secure_password validations: false, and valid_password? returns false on a blank digest, so a pure-SSO account is simply a row with no digest. (Saleor needs an "unusable password" sentinel only because Django's column is not nullable.) The first has no demand in commerce. Against that, moving the digest off the model would break Spree.customer_class pluggability: the Path B recipe below aliases password_digest to an app's legacy column on the app's own model, which only works while the credential belongs to the model. A separate table would force every custom user class to adopt Spree's identity table too — the opposite of "database tables stay configurable".
  • SSO-only shops remove the :email strategy — there is no separate toggle (2026-08-03). Spree.admin_authentication_strategies.remove(:email) makes password login structurally unreachable: the auth controllers resolve every login through the registry and return invalid_provider (400) for an unregistered key. No boolean preference — a second source of truth could disagree with the registry.
  • Password policy is a plain Rails validator (2026-08-03). Length bounds stay preferences — Spree::Config[:minimum_password_length] (default 8 — NIST 800-63B, no composition rules; matches Saleor) and [:maximum_password_length] (the bcrypt 72-byte cap) — because they are values. The policy itself is a class, so it follows the Spree.<name> accessor convention used by customer_class/base_class/tax_provider, not a Spree::Config string preference: Spree.password_validator, defaulting to Spree::PasswordLengthValidator, registered in engine.rb like tax_provider. Assigning a different ActiveModel::Validator replaces the policy wholesale. Not Spree::Dependencies either — that registry is for services and workflows you call, whereas this is a class-level policy like the other Spree. accessors. Vendure needs a bespoke PasswordValidationStrategy because TypeScript has no validates_with; Rails already has the extension point, and errors on :password reach the dashboard form through the existing 422 → mapSpreeErrorsToForm path, so a custom validator's message is the user-facing reason with no new plumbing.
  • The dashboard login page is driven by the strategy registry, not hardcoded (2026-08-03). See Phase 7.

User → Customer/AdminUser rename

  • Spree.user_class → Spree.customer_class. Deprecation alias for one release.
  • Spree.admin_user_class stays as-is. Model stays Spree::AdminUser, accessor stays admin_user_class. Only the default implementation changes from LegacyAdminUser to AdminUser.
  • Default models: Spree::Customer and Spree::AdminUser. Replace Spree::LegacyUser and Spree::LegacyAdminUser.
  • Spree::Customer includes has_secure_password and all auth concerns by default. Production-ready out of the box, not a "legacy" placeholder.
  • Spree::AdminUser includes has_secure_password and admin auth concerns.
  • Prefix IDs: cust_ for Customer, adm_ for AdminUser.
  • Concerns renamed + consolidated: Spree::UserMethods → Spree::CustomerMethods, Spree::AdminUserMethods stays as-is. Aliases for one release. CustomerMethods absorbs Spree::UserAddress and Spree::UserPaymentSource (today the generator injects all three) so a custom user class needs exactly one include — include Spree::CustomerMethods — to be a valid Spree.customer_class.
  • Database tables stay configurable. Spree.customer_class can point to any model — User, Customer, whatever the app uses. The rename is about the Spree interface and defaults, not forcing a table name.

Design Details

Spree::Customer (replaces LegacyUser)

class Spree::Customer < Spree.base_class
  has_prefix_id :cust

  has_secure_password

  include Spree::CustomerMethods      # orders, addresses, payments, wishlists
  include Spree::Metafields
  include Spree::Metadata

  has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy

  validates :email, presence: true, uniqueness: { case_sensitive: false }

  # Account security
  attribute :failed_attempts, :integer, default: 0
  attribute :locked_at, :datetime

  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

Spree::AdminUser (replaces LegacyAdminUser)

class Spree::AdminUser < Spree.base_class
  has_prefix_id :adm

  has_secure_password

  include Spree::AdminUserMethods      # roles, permissions, store access
  include Spree::Metafields
  include Spree::Metadata

  has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy

  validates :email, presence: true, uniqueness: { case_sensitive: false }

  attribute :failed_attempts, :integer, default: 0
  attribute :locked_at, :datetime
end

Refresh Token Model

class Spree::RefreshToken < Spree.base_class
  has_prefix_id :rt

  belongs_to :user, polymorphic: true  # Customer or AdminUser

  has_secure_token :token

  validates :token, :expires_at, presence: true

  scope :active, -> { where('expires_at > ?', Time.current) }
  scope :expired, -> { where('expires_at <= ?', Time.current) }

  attribute :expires_at, :datetime
  attribute :ip_address, :string
  attribute :user_agent, :string

  def expired?
    expires_at <= Time.current
  end

  def rotate!
    transaction do
      destroy!
      self.class.create!(
        user: user,
        expires_at: 30.days.from_now,
        ip_address: ip_address,
        user_agent: user_agent
      )
    end
  end
end

Auth API Endpoints

# Store API
POST   /api/v3/store/auth/login           # provider-dispatched login (email default, OAuth/SSO/custom JWT via `provider` key) → access JWT + refresh token
POST   /api/v3/store/auth/refresh         # refresh token → new access JWT + rotated refresh token
POST   /api/v3/store/auth/logout          # revoke refresh token

POST   /api/v3/store/customers            # register → JWT + refresh token
POST   /api/v3/store/customer/password_resets          # request reset email
PATCH  /api/v3/store/customer/password_resets/:token   # consume token, set password → JWT

# Admin API
POST   /api/v3/admin/auth/login           # email+password → access JWT + refresh token
POST   /api/v3/admin/auth/refresh         # refresh token → new access JWT
POST   /api/v3/admin/auth/logout          # revoke refresh token

Auth Flow

1. Customer visits storefront
2. Login: POST /auth/login { email, password }
   → EmailPasswordStrategy.authenticate(email, password, request_env)
   → Strategy returns success(customer) or failure(message)
   → Controller issues: { access_token: JWT (15 min), refresh_token: "rt_xxx" (30 days) }

3. API requests: Authorization: Bearer <access_token>
   → JwtAuthentication concern validates, sets current_customer

4. Token expires (15 min)
   → POST /auth/refresh { refresh_token: "rt_xxx" }
   → Validate refresh token, rotate it, issue new access JWT
   → Returns: { access_token: new JWT, refresh_token: "rt_yyy" (rotated) }

5. Logout: POST /auth/logout { refresh_token: "rt_xxx" }
   → Delete refresh token from DB

Configuration

Spree.configure do |config|
  # Customer auth strategies (extensible)
  config.store_authentication_strategies = {
    email: Spree::Authentication::Strategies::EmailPasswordStrategy
    # Add custom: google: MyApp::Auth::GoogleStrategy
  }

  # Admin auth strategies
  config.admin_authentication_strategies = {
    email: Spree::Authentication::Strategies::EmailPasswordStrategy
  }

  # JWT config
  config.jwt_access_token_expiry = 15.minutes
  config.jwt_secret = Rails.application.secret_key_base

  # Refresh token config
  config.refresh_token_expiry = 30.days

  # Account lockout
  config.max_failed_login_attempts = 5
  config.lockout_duration = 30.minutes
end

Custom Auth Provider Example

# Using Auth0
class MyApp::Auth::Auth0Strategy < Spree::Authentication::Strategies::BaseStrategy
  def provider
    :auth0
  end

  def authenticate(email, token, request_env = {})
    # Verify Auth0 JWT
    payload = Auth0Client.verify(token)
    user = find_user_by_email(payload['email']) ||
           find_or_create_user_from_oauth(
             provider: 'auth0',
             uid: payload['sub'],
             info: { email: payload['email'], name: payload['name'] }
           )
    success(user)
  rescue Auth0Client::InvalidToken => e
    failure(e.message)
  end
end

# Register in config
Spree.configure do |config|
  config.store_authentication_strategies[:auth0] = MyApp::Auth::Auth0Strategy
end

Migration Path

Phase 1: Customer/AdminUser models + has_secure_password

class CreateSpreeCustomersAndAdminUsers < ActiveRecord::Migration[7.2]
  def change
    # If app uses custom user tables, these aren't needed.
    # For new installs using Spree defaults:

    create_table :spree_customers do |t|
      t.string :email, null: false
      t.string :password_digest, null: false
      t.integer :failed_attempts, null: false, default: 0
      t.datetime :locked_at
      t.jsonb :metadata
      t.timestamps
    end
    add_index :spree_customers, :email, unique: true

    create_table :spree_admin_users do |t|
      t.string :email, null: false
      t.string :password_digest, null: false
      t.integer :failed_attempts, null: false, default: 0
      t.datetime :locked_at
      t.jsonb :metadata
      t.timestamps
    end
    add_index :spree_admin_users, :email, unique: true

    # Refresh tokens
    create_table :spree_refresh_tokens do |t|
      t.string :token, null: false
      t.references :user, polymorphic: true, null: false
      t.datetime :expires_at, null: false
      t.string :ip_address
      t.string :user_agent
      t.timestamps
    end
    add_index :spree_refresh_tokens, :token, unique: true
    add_index :spree_refresh_tokens, [:user_type, :user_id]
    add_index :spree_refresh_tokens, :expires_at
  end
end

Phase 2: Data migration (for existing Devise-based installs) — implemented

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 reference that named the old customer class (Spree::User → Spree.customer_class) on spree_role_users, spree_refresh_tokens, spree_user_identities, spree_api_keys (created_by_type + revoked_by_type), and spree_customer_group_users (whose type column was renamed user_type → customer_type); admin rows (Spree::AdminUser) are untouched since that class name is unchanged. Admins are handled in place — spree_admin_users keeps its table and class, so the task just backfills password_digest from 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 — since Devise is gone in 6.0 and a former pepper can't be introspected — also aborts when Devise is absent until the operator confirms none was used (CONFIRM_NO_PEPPER=true). A preflight aborts with the offending ids when a source row has a blank email or an email already owned by a different customer (SKIP_INVALID_ROWS=true skips them instead) — otherwise the renamed customer_id FKs could point at a customer that never migrated. The source table is left in place as a safety net (a later cleanup drops it). Idempotent — re-running skips ids already in spree_customers.

Path B — keep a custom user model (documented recipe, no gem code). No data migration and no 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

  • Spree.user_class → Spree.customer_class (deprecation alias for user_class)
  • Spree.admin_user_class stays as-is
  • Spree::UserMethods → Spree::CustomerMethods (deprecation alias)
  • Spree::AdminUserMethods stays as-is
  • Spree::LegacyUser → Spree::Customer (new default)
  • Spree::LegacyAdminUser → Spree::AdminUser (new default, production-ready)
  • 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):

  • 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.
  • The two historical spree_admin_users ALTER migrations (add_first_and_last_name_to_spree_admin_class, add_selected_locale_to_spree_admin_users) were removed: unlike the spree_users ALTERs they carried no table_exists? guard, so on a fresh gem-owned install — where nothing creates spree_admin_users before them — they aborted db:migrate. Their columns already ship in create_spree_customers_and_admin_users and the dummy generator, and existing installs ran them long ago.
  • 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. Done across core, api and emails: the .user / .user_id reads and associate_user! / disassociate_user! calls are migrated too, so the first-party suites no longer emit any customer-rename deprecation warning. Three call sites read a different target and were renamed accordingly — Address#user → #owner, not #customer. Genuinely non-deprecated user names were left alone: Spree::Core::Pricing::Context#user, the analytics handler's user:, and the auth strategies' user_class (which holds a customer or an admin class).
  • Spree::Cart#associate_user! was deleted rather than kept. Cart is new in 6.0, so it never had a pre-rename name to bridge; only Spree::Order keeps the deprecated pair.
  • The users associations are bridged, not left as-is. GiftCard and Promotion::Rules::User gained a real has_many :customers, with users kept beside it as a Rails 8.1 deprecated: true twin; CustomerGroup already had both, so its users was simply marked. The promotion rule's hand-written customer_ids / customer_ids= delegators were deleted — those now come from the customers association itself, which keeps one write path rather than two association caches over the same join rows. Role#users (paired with admin_users as a customer-vs-admin split) and PriceRules::UserRule#users (a plain method over a user_ids preference column, on a superseded rule) were deliberately left alone.
  • The Admin API takes customer_id only — the legacy user_id param is gone from Admin::OrdersController and Admin::GiftCardsController, along with user_id in GiftCard's Ransack allowlist, so a back-office client has one spelling. This also repairs a read/write asymmetry: the gift card serializer already returned customer_id while the controller accepted only user_id, so a client could not round-trip what it read. @spree/admin-sdk params, the dashboard's gift-card form mapper and table filter, and the generated OpenAPI spec were updated to match. The Store API is untouched.

Phase 4: Refresh tokens, rate limiting, account lockout

Shipped earlier (5.4 + prior 6.0 work):

  • Spree::RefreshToken model (issue/rotate/revoke) — create_for / rotate! / revoke_all_for.
  • AuthController issues refresh tokens alongside access JWTs, and POST /auth/refresh + POST /auth/logout for both store (refresh token in body) and admin (HttpOnly cookie).
  • Rate limiting (Rails rate_limit) on login/refresh/register/password-reset + a global per-caller throttle + X-RateLimit-* headers, all config-driven via Spree::Api::Config[:rate_limit_*]: one bucket per caller across all v3 controllers (scope: 'api_v3'), split by credential — secret keys get rate_limit_per_secret_key (600/min) per key, publishable keys get rate_limit_per_key (300/min) per key + client IP (per visitor, never per storefront), keyless/JWT traffic per IP.
  • Account-lockout methods + failed_attempts/locked_at columns on Customer/AdminUser.

Landed:

  • Account-lockout enforcement. EmailPasswordStrategy#authenticate now blocks locked accounts (distinct "temporarily locked" message), records a failed attempt on a bad password, and resets on success — respond_to?-guarded so a custom customer_class without lockout still authenticates. One hook covers both store and admin login.
  • Config-driven thresholds. Lockout logic extracted into a shared Spree::AccountLockout concern (included by both models) reading Spree::Config[:max_failed_login_attempts] (5) and [:lockout_duration] (1800s) instead of the previously hardcoded 5 / 30.minutes.
  • Admin logout rate-limit added to match the store side.
  • Dashboard login surfaces the server message (@spree/dashboard login.tsx) so the lockout response reaches the UI instead of a generic error — bad credentials and lockout share an error code, so the message is the only distinguishing signal.

Not pursued: hashing refresh tokens at rest (they're already random + expiring, and login is rate-limited).

Open gap — no minimum password length. Today Spree::Customer and Spree::AdminUser validate only confirmation and the bcrypt 72-byte cap, so a one-character admin password is valid. Of the platforms surveyed, Medusa ships no policy at all (a bare presence check, and no hook to add one), Vendure defaults to a deliberately permissive 4 behind a replaceable strategy, and Saleor enforces 8 via a single Django MinimumLengthValidator. Close this before 6.0 ships:

# spree/core/lib/spree/core/configuration.rb — values are preferences
preference :minimum_password_length, :integer, default: 8
preference :maximum_password_length, :integer, default: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED

# spree/core/lib/spree/core/engine.rb — the policy is a class, like tax_provider
Rails.application.config.spree.password_validator = Spree::PasswordLengthValidator

# Host app replaces the policy wholesale:
Spree.password_validator = MyApp::PasswordValidator

Applies to both models via the shared Spree::PasswordPolicy concern, which is a thin validate hook delegating to Spree.password_validator. The maximum is a correctness guard rather than policy — bcrypt truncates past 72 bytes, so without it a long passphrase and its 72-byte prefix are the same password.

Raising the floor on an existing install invalidates no stored digest — the validation runs on password, which is only present when a password is being set — so upgrades are safe and existing short passwords keep working until their next change.

Phase 5: Remove Devise + all authentication generators — core/api done

Landed (scoped to spree/core + spree/api):

  • Deleted the spree/core/lib/generators/spree/authentication/devise/ and custom/ generators (kept dummy/ for the test harness).
  • Deleted Spree::LegacyUser and Spree::LegacyAdminUser (4 specs repointed to Spree.customer_class).
  • Removed the Devise bridges — Spree::AdminUserMethods::DeviseNotifications and CustomerMethods::SkipPasswordValidation — plus their spec/controller callers. Live admin auth emails already flow through the admin_user.password_reset_requested event subscriber; password-less admin-created customers work via has_secure_password validations: false.
  • Removed the core devise: i18n block and reworded the Devise comments.
  • Flipped the root-gem spree:install --authentication default to nil (a plain install scaffolds no auth — the gem owns it) and dropped the devise dispatch branch; removed the common_rake devise shell-out.
  • Rewrote the documented rails new -m template.rb install to be headless and gem-owned: drops the devise and spree_admin gems, installs core + API only (no --authentication/--user_class flags), and removes the obsolete Procfile.dev step (bin/dev runs the server directly). USE_LOCAL_SPREE now takes a monorepo path so the template resolves edge gems. (The spree-starter clone behind create-spree-app/server:setup is still Devise — that is Phase 5b.)

Deferred (NOT done here):

  • spree/admin's Devise controllers/generators (user_sessions_controller, user_passwords_controller, spree/admin/devise/) ride the wholesale admin-gem removal (6.0-admin-spa.md).
  • The defined?(Devise) guards in spree:upgrade:migrate_users_to_customers are kept (defensive for installs migrating off Devise). No Warden references existed in core/api.

Phase 5b: spree-starter changes

The starter currently ships the host-app auth code the generator produced. At 6.0:

  • Remove app/models/spree/user.rb (the Devise Spree::User model)
  • Remove the devise gem from the Gemfile
  • Remove lib/spree/authentication_helpers.rb and its to_prepare wiring in config/initializers/spree.rb
  • Remove devise_for routes and the Devise.parent_controller initializer block
  • Ship the Path A migration rake task invocation in the upgrade guide

Phase 6: Cleanup (still 6.0) — partially done

  • Deprecation aliases kept through 6.0 (revised): Spree.user_class/user_class=, Spree::UserMethods, Spree::DeprecatedCustomerAlias, and the :user factory alias all remain for 6.0. This supersedes the earlier "remove the user_class alias in 6.0" plan; their removal is extracted to Phase 8 (6.1). This covers the Ruby aliases only — the Admin API's user_id request param was dropped outright in 6.0 (see Phase 3), since the back-office API is a 6.0 surface with no installed base to carry.
  • Spree::OauthAccessToken: nothing remains (extracted upstream to legacy_api_v2). No-op. ✓
  • Devise / user_class docs sweep — done: rewrote the Devise-as-default pages (customization/authentication, admin/authentication, adding_spree_to_rails_app, customization/quickstart, admin.mdx) around the gem-owned Spree::Customer/AdminUser + has_secure_password + custom-model recipe, and swept Spree.user_class → Spree.customer_class across the incidental docs (kept the alias notes + historical upgrade guides). The multi-tenant quickstart's Devise example was left intact (it targets a Devise-based custom model) with a clarifying note.
  • Deferred: the net-new docs/developer/upgrades/5.6-to-6.0.mdx (with the Path A/B migrate-users section), the spree_users table teardown task, and the search-area multi_search alias removal.

Phase 7: SSO / OIDC login in the React dashboard (6.0) — not started

The registry supports SSO-only admins today, but the dashboard cannot see it. packages/dashboard/src/routes/login.tsx hardcodes the email/password form, so a shop that runs Spree.admin_authentication_strategies.remove(:email) still gets a password form that can only ever return invalid_provider. There is also no redirect-based login path at all: BaseStrategy assumes the client posts credentials to auth/login, which fits Auth0-style token verification but not the browser redirect that Microsoft Entra ID, Okta and Google Workspace actually use. Both halves are needed for the enterprise SSO story.

Strategy self-description (spree/core). BaseStrategy grows a small class-level surface so the registry can describe itself, with defaults that keep existing custom strategies working unchanged:

  • kind — :password (client posts credentials) or :redirect (client sends the browser to the IdP). Defaults to :password.
  • label — human-readable provider name for the button ("Microsoft Entra ID").
  • authorization_url(state:) — redirect providers only; where to send the browser.

Registry accepts configured factories (spree/core). Both auth controllers currently do strategy_class.new(params:, request_env:, user_class:), so the registry can only hold bare classes — which cannot carry per-registration config (issuer, client id/secret, label), and cannot express the same class registered twice under different keys. StrategyRegistry entries become "a class or an object responding to #build(params:, request_env:, user_class:)", and the controllers branch on respond_to?(:build). Existing class registrations are untouched:

Spree.admin_authentication_strategies.add(
  :entra,
  Spree::Authentication::Strategies::OidcStrategy.configure(
    issuer: 'https://login.microsoftonline.com/<tenant>/v2.0',
    client_id: ENV['ENTRA_CLIENT_ID'],
    client_secret: ENV['ENTRA_CLIENT_SECRET'],
    label: 'Microsoft Entra ID'
  )
)

Reference provider: one generic OIDC strategy (2026-08-03). Spree::Authentication::Strategies::OidcStrategy, configured by issuer discovery (.well-known/openid-configuration) plus client credentials, covers Entra ID, Okta, Google Workspace, Keycloak and Auth0 with no per-vendor code — the same choice commercetools made for enterprise SSO, which ships OIDC only and documents per-vendor setup guides rather than per-vendor classes. No named EntraStrategy; vendor specificity lives in docs and in the issuer value.

Discovery endpoint (spree/api) — Admin API only in 6.0. GET /api/v3/admin/auth/providers, unauthenticated because it is consumed before login, returning the registered strategies. No store twin: the dashboard is the login UI Spree ships and controls, whereas headless storefronts own theirs and already know which strategies they registered. Revisit if storefront authors ask for it.

{ "providers": [
    { "key": "email", "kind": "password" },
    { "key": "entra", "kind": "redirect", "label": "Microsoft Entra ID",
      "authorization_url": "https://login.microsoftonline.com/…" }
] }

Two constraints, both non-negotiable: it exposes only provider keys, kinds, labels and authorization URLs — never client secrets, never strategy class names — and it sits behind the existing auth rate limiter, since an open endpoint listing a shop's IdP is a fingerprinting surface.

OAuth callback (spree/api). A new GET /api/v3/admin/auth/callback/:provider completes the redirect flow: it verifies the state parameter (CSRF), hands the authorization code to the strategy, resolves the user through Spree::UserIdentity, then issues the same access JWT + refresh-token cookie pair the password path already issues. No new session mechanism — the redirect flow terminates in exactly the tokens Phase 4 defined. Admin identities resolve with user_class: Spree.admin_user_class, so an SSO admin and an SSO customer with the same email stay distinct records.

Account resolution — three rules, settled 2026-08-03. The callback resolves an IdP subject to an AdminUser in this order:

  1. Known identity — a Spree::UserIdentity matching (provider, uid, user_type) already exists. Log in.
  2. Existing admin, first SSO login — no identity yet, but an AdminUser has the same email and the IdP asserts email_verified: true. Link a new UserIdentity to that account and log in. This is what makes the migration path work: a shop registers Entra and its existing staff simply sign in, with no password round-trip — which matters most for the shop that also removed :email. The verified-claim requirement is not optional; matching on an unverified email claim lets anyone who can set their IdP email to a staff address take over that account. An explicit email_verified: false is always refused. A missing claim is a separate case (2026-08-04): Entra omits it for work accounts, so a strict reading would block first-login linking on the reference provider. Absence therefore falls to per-provider trust_unverified_email: (default off), enabled only for a directory that owns its addresses — never for a provider where a person picks their own email.
  3. Unknown subject — no identity, no email match. Rejected. Admin accounts never auto-provision, or every member of a corporate Entra tenant becomes store staff. The person must be invited through the existing invitation flow first. Integrators may opt into JIT provisioning per strategy.

Rule 3 rejects a person who authenticated successfully with their IdP, so a generic "authentication failed" reads as a broken login. The callback redirects to the dashboard login page with a distinct error code, and the page explains that the account is not authorised for this store and an administrator must send an invitation. Customers keep today's behaviour — UserIdentity.find_or_create_from_oauth already auto-creates a Customer on first social login, which is what shoppers expect from "Sign in with Google" and carries none of the staff blast radius.

How IdP group claims map to Spree roles stays with the strategy, not core.

Dynamic login page (packages/dashboard). login.tsx fetches the provider list and renders from it:

  • email present → the password form, as today.
  • Redirect providers present → one button each, sending the browser to authorization_url.
  • Both → form plus buttons, separated by a divider.
  • No email → buttons only, and the /forgot-password link is hidden (password reset is meaningless with no password).
  • Fetch fails → an error state, not a fallback password form. Falling back is the safer default for availability but the wrong one here: on an SSO-only shop it renders a form that cannot work.

All provider labels and the divider copy go through i18next into every locale file, per the dashboard translation rule.

Phase 8: Remove deprecation aliases (6.1)

Breaking cleanup for 6.1 — remove the compatibility shims kept through 6.0 (all tagged "remove in Spree 6.1" in code), after sweeping any remaining first-party callers off them:

  • Spree.user_class / Spree.user_class= shims in spree/core/lib/spree/core.rb (callers move to Spree.customer_class).
  • Spree::UserMethods = CustomerMethods alias (spree/core/app/models/concerns/spree/user_methods.rb).
  • Spree::DeprecatedCustomerAlias — the deprecated user / user_id readers + writers — from the 10 customer-facing models.
  • The :user alias on the :customer factory (spree/core/lib/spree/testing_support/factories/user_factory.rb).

Constraints on Current Work

  • Don't add new Devise dependencies. No new devise_for, no new Devise controller inheritance.
  • Use Spree.user_class / Spree.admin_user_class for now — user_class will become customer_class in 6.0, admin_user_class stays.
  • New auth features should use the strategy pattern. Don't bypass BaseStrategy for auth logic.
  • JWT tokens are the only API auth mechanism. No cookie sessions in API controllers.

Open Questions

None at this time. The two Phase 7 questions raised on 2026-08-03 are both resolved in that phase: a single generic OIDC strategy ships as the reference provider (no per-vendor classes), and provider discovery is Admin API only in 6.0.

References

  • Current auth strategy: spree/core/app/models/spree/authentication/strategies/base_strategy.rb
  • Current JWT implementation: spree/api/app/controllers/concerns/spree/api/v3/jwt_authentication.rb
  • Current user models: spree/core/app/models/spree/legacy_user.rb, spree/core/app/models/spree/legacy_admin_user.rb
  • Current user concerns: spree/core/app/models/concerns/spree/user_methods.rb, spree/core/app/models/concerns/spree/admin_user_methods.rb
  • Devise generators (to be removed): spree/core/lib/generators/spree/authentication/devise/
  • Related plan: 6.0-admin-spa.md (React admin removes Rails admin, kills Devise dependency)
  • Related plan: 6.0-channels-catalogs-b2b.md (Company → CompanyContact references customer/staff)