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.

Enforce account lockout in the auth strategy (platform-auth Phase 4)

Łukasz Adamczyk47f3539ee98e
diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
index ec8be3f480..46dc12f0ef 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
@@ -9,6 +9,7 @@ module Spree
rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSE
rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE
+ rate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :logout, with: RATE_LIMIT_RESPONSE
skip_before_action :authenticate_admin!, only: [:create, :refresh, :logout]
diff --git a/spree/core/app/models/concerns/spree/account_lockout.rb b/spree/core/app/models/concerns/spree/account_lockout.rb
new file mode 100644
index 0000000000..454bbaf6b2
--- /dev/null
+++ b/spree/core/app/models/concerns/spree/account_lockout.rb
@@ -0,0 +1,33 @@
+module Spree
+ # Failed-login tracking and temporary account lockout, shared by the default
+ # auth models (Customer, AdminUser). Thresholds are configuration-driven via
+ # +Spree::Config[:max_failed_login_attempts]+ and +Spree::Config[:lockout_duration]+
+ # (seconds). Enforcement lives in the authentication strategy — including this
+ # concern opts a model in, but nothing locks until the login flow records attempts.
+ module AccountLockout
+ extend ActiveSupport::Concern
+
+ included do
+ attribute :failed_attempts, :integer, default: 0
+ end
+
+ # @return [Boolean] whether the account is currently within its lockout window
+ def locked?
+ locked_at.present? && locked_at > Spree::Config[:lockout_duration].seconds.ago
+ end
+
+ # Records a failed login attempt, locking the account once the configured
+ # threshold is reached.
+ # @return [void]
+ def record_failed_attempt!
+ increment!(:failed_attempts)
+ update!(locked_at: Time.current) if failed_attempts >= Spree::Config[:max_failed_login_attempts]
+ end
+
+ # Clears the failed-attempt counter and any lockout. Call on successful login.
+ # @return [void]
+ def reset_failed_attempts!
+ update!(failed_attempts: 0, locked_at: nil)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/admin_user.rb b/spree/core/app/models/spree/admin_user.rb
index 8f3e4fec1d..fb26b2c6b9 100644
--- a/spree/core/app/models/spree/admin_user.rb
+++ b/spree/core/app/models/spree/admin_user.rb
@@ -7,12 +7,11 @@ module Spree
has_secure_password validations: false
include Spree::AdminUserMethods
+ include Spree::AccountLockout
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.
@@ -23,19 +22,5 @@ module Spree
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/email_password_strategy.rb b/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb
index 3d5db32992..25dbdb51b9 100644
--- a/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb
+++ b/spree/core/app/models/spree/authentication/strategies/email_password_strategy.rb
@@ -11,10 +11,13 @@ module Spree
user = find_user_by_email(email)
return failure('Invalid email or password') unless user
+ return failure('Account temporarily locked. Try again later.') if user.respond_to?(:locked?) && user.locked?
if validate_password(user, password)
+ user.reset_failed_attempts! if user.respond_to?(:reset_failed_attempts!) && user.failed_attempts.to_i.positive?
success(user)
else
+ user.record_failed_attempt! if user.respond_to?(:record_failed_attempt!)
failure('Invalid email or password')
end
rescue => e
@@ -29,14 +32,14 @@ module Spree
private
def validate_password(user, password)
- # Try Devise's valid_password? method first (most common)
+ # Duck-typed so any customer_class works: prefer valid_password?
+ # (defined by the gem models and legacy/custom models alike), then
+ # fall back to has_secure_password's authenticate.
if user.respond_to?(:valid_password?)
user.valid_password?(password)
- # Fallback to authenticate method (for has_secure_password)
elsif user.respond_to?(:authenticate)
user.authenticate(password).present?
else
- # No password authentication available
Rails.logger.warn "User class #{user.class} does not implement password authentication"
false
end
diff --git a/spree/core/app/models/spree/customer.rb b/spree/core/app/models/spree/customer.rb
index 839d660ded..adf46a9116 100644
--- a/spree/core/app/models/spree/customer.rb
+++ b/spree/core/app/models/spree/customer.rb
@@ -7,17 +7,17 @@ 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.
+ # `validations: false` — password presence is not enforced at the model level;
+ # storefront registration owns that requirement, and admin-created customers
+ # claim their account via password reset.
has_secure_password validations: false
include Spree::CustomerMethods
+ include Spree::AccountLockout
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?+.
@@ -30,19 +30,5 @@ module Spree
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/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index 0c1a84c1ba..ec9a78756a 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -120,6 +120,10 @@ module Spree
preference :admin_password_reset_expires_in, :integer, default: 15 # admin password reset token expiration time in minutes
preference :customer_password_reset_expires_in, :integer, default: 15 # password reset token expiration time in minutes
+ # account lockout
+ preference :max_failed_login_attempts, :integer, default: 5 # failed login attempts before an account is locked
+ preference :lockout_duration, :integer, default: 1800 # lockout duration in seconds (30 minutes)
+
# gift cards
preference :gift_card_batch_web_limit, :integer, default: 500 # number of gift card codes to be generated in the web process, more than this will be generated in a background job
preference :gift_card_batch_limit, :integer, default: 50_000
diff --git a/spree/core/spec/models/spree/admin_user_spec.rb b/spree/core/spec/models/spree/admin_user_spec.rb
index 7c4c7173bf..122210b465 100644
--- a/spree/core/spec/models/spree/admin_user_spec.rb
+++ b/spree/core/spec/models/spree/admin_user_spec.rb
@@ -3,6 +3,10 @@ require 'spec_helper'
describe Spree.admin_user_class, type: :model do
let(:admin_user) { create(:admin_user) }
+ it_behaves_like 'account lockout' do
+ let(:lockable) { admin_user }
+ end
+
describe 'password reset tokens' do
it 'round-trips through find_by_password_reset_token' do
token = admin_user.generate_token_for(:password_reset)
@@ -18,31 +22,13 @@ describe Spree.admin_user_class, type: :model do
# The token payload keys off the password salt/digest so it invalidates
# when the password changes. has_secure_password provides #password_salt
# (derived from password_digest); the generator also falls back through
- # encrypted_password/password_digest for legacy/Devise schemas without a
- # password_salt column, so it never raises NameError.
+ # encrypted_password for a legacy bcrypt column on a custom model without a
+ # password_salt, so it never raises NameError.
it 'generates a password reset token from the password digest' do
expect(admin_user.generate_token_for(:password_reset)).to be_present
end
end
- describe '#send_devise_notification (Devise bridge)' do
- let(:mail) { double(deliver_later: true) }
-
- it 'routes reset password instructions through Spree::AdminUserMailer' do
- expect(Spree::AdminUserMailer).to receive(:password_reset_email).
- with(admin_user, 'devise-token', Spree::Store.default).and_return(mail)
-
- admin_user.send_devise_notification(:reset_password_instructions, 'devise-token', {})
- end
-
- it 'routes confirmation instructions through Spree::AdminUserMailer' do
- expect(Spree::AdminUserMailer).to receive(:confirmation_email).
- with(admin_user, 'devise-token', Spree::Store.default).and_return(mail)
-
- admin_user.send_devise_notification(:confirmation_instructions, 'devise-token', {})
- end
- end
-
describe '#can_be_deleted?' do
subject { admin_user.can_be_deleted? }
diff --git a/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb b/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb
index d1877963bc..7a9ee01b2a 100644
--- a/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb
+++ b/spree/core/spec/models/spree/authentication/strategies/email_password_strategy_spec.rb
@@ -19,7 +19,7 @@ describe Spree::Authentication::Strategies::EmailPasswordStrategy do
context 'with valid credentials' do
before do
user # ensure user exists
- # Mock password validation since LegacyUser doesn't have authentication
+ # Stub password validation to isolate the strategy from the model's digest
allow(user).to receive(:valid_password?).with('password123').and_return(true)
allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(user)
end
@@ -61,6 +61,55 @@ describe Spree::Authentication::Strategies::EmailPasswordStrategy do
end
end
+ describe 'account lockout' do
+ before do
+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(user)
+ end
+
+ it 'fails a locked account without checking the password' do
+ allow(user).to receive(:locked?).and_return(true)
+ expect(strategy).not_to receive(:validate_password)
+
+ result = strategy.authenticate
+
+ expect(result).not_to be_success
+ expect(result.error).to eq('Account temporarily locked. Try again later.')
+ end
+
+ it 'records a failed attempt on an invalid password' do
+ allow(user).to receive(:valid_password?).with('password123').and_return(false)
+ expect(user).to receive(:record_failed_attempt!)
+
+ strategy.authenticate
+ end
+
+ it 'resets failed attempts on success when attempts were recorded' do
+ allow(user).to receive(:valid_password?).with('password123').and_return(true)
+ allow(user).to receive(:failed_attempts).and_return(3)
+ expect(user).to receive(:reset_failed_attempts!)
+
+ expect(strategy.authenticate).to be_success
+ end
+
+ it 'does not reset when there were no failed attempts' do
+ allow(user).to receive(:valid_password?).with('password123').and_return(true)
+ allow(user).to receive(:failed_attempts).and_return(0)
+ expect(user).not_to receive(:reset_failed_attempts!)
+
+ expect(strategy.authenticate).to be_success
+ end
+
+ it 'authenticates a user model that does not implement lockout' do
+ bare_user = double('user without lockout', valid_password?: true)
+ allow(strategy).to receive(:find_user_by_email).with('[email protected]').and_return(bare_user)
+
+ result = strategy.authenticate
+
+ expect(result).to be_success
+ expect(result.value).to eq(bare_user)
+ end
+ end
+
context 'when email is blank' do
let(:params) { { email: '', password: 'password123' } }
diff --git a/spree/core/spec/models/spree/customer_spec.rb b/spree/core/spec/models/spree/customer_spec.rb
index e88b379bfa..9b12d4ceba 100644
--- a/spree/core/spec/models/spree/customer_spec.rb
+++ b/spree/core/spec/models/spree/customer_spec.rb
@@ -47,22 +47,8 @@ describe Spree::Customer, type: :model do
end
end
- describe 'account lockout' do
- it 'is not locked by default' do
- expect(customer).not_to be_locked
- end
-
- it 'locks after five failed attempts' do
- 5.times { customer.record_failed_attempt! }
- expect(customer).to be_locked
- end
-
- it 'clears the lock on reset' do
- 5.times { customer.record_failed_attempt! }
- customer.reset_failed_attempts!
- expect(customer.reload).not_to be_locked
- expect(customer.failed_attempts).to eq(0)
- end
+ it_behaves_like 'account lockout' do
+ let(:lockable) { customer }
end
describe 'prefixed id' do
diff --git a/spree/core/spec/support/shared_examples/account_lockout.rb b/spree/core/spec/support/shared_examples/account_lockout.rb
new file mode 100644
index 0000000000..0018343f79
--- /dev/null
+++ b/spree/core/spec/support/shared_examples/account_lockout.rb
@@ -0,0 +1,41 @@
+# Shared behavior for models that include Spree::AccountLockout.
+# The including example group must define `let(:lockable)` returning a persisted
+# record of such a model. Preferences set here are reset between examples by the
+# global reset_spree_preferences before(:each) hook.
+RSpec.shared_examples 'account lockout' do
+ describe 'account lockout' do
+ it 'is not locked by default' do
+ expect(lockable).not_to be_locked
+ end
+
+ it 'locks after the configured number of failed attempts' do
+ Spree::Config[:max_failed_login_attempts] = 2
+
+ lockable.record_failed_attempt!
+ expect(lockable).not_to be_locked
+
+ lockable.record_failed_attempt!
+ expect(lockable.reload).to be_locked
+ end
+
+ it 'clears the lock and counter on reset' do
+ Spree::Config[:max_failed_login_attempts] = 2
+ 2.times { lockable.record_failed_attempt! }
+
+ lockable.reset_failed_attempts!
+
+ expect(lockable.reload).not_to be_locked
+ expect(lockable.failed_attempts).to eq(0)
+ end
+
+ it 'unlocks once the lockout_duration window has passed' do
+ Spree::Config[:max_failed_login_attempts] = 1
+ Spree::Config[:lockout_duration] = 15.minutes.to_i
+ lockable.record_failed_attempt!
+ expect(lockable).to be_locked
+
+ lockable.update_column(:locked_at, 16.minutes.ago)
+ expect(lockable).not_to be_locked
+ end
+ end
+end