Skip to content

Commit

Permalink
Merge pull request #1726 from plataformatec/failed_attempts
Browse files Browse the repository at this point in the history
Setting failed_attempts to 0 after sign in
  • Loading branch information
josevalim committed Mar 19, 2012
2 parents a1376ac + e6af976 commit e92ae37
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 11 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.rdoc
@@ -1,3 +1,8 @@
== trunk (2.1.0.rc2)

* bug fix
* `failed_attempts` being set to zero after sign ins (by @rodrigoflores)

== 2.1.0.rc

* enhancements
Expand Down
7 changes: 7 additions & 0 deletions lib/devise/hooks/lockable.rb
@@ -0,0 +1,7 @@
# After each sign in, if resource responds to failed_attempts, sets it to 0
# This is only triggered when the user is explicitly set (with set_user)
Warden::Manager.after_set_user :except => :fetch do |record, warden, options|
if record.respond_to?(:failed_attempts) && warden.authenticated?(options[:scope])
record.update_attribute(:failed_attempts, 0)
end
end
4 changes: 2 additions & 2 deletions lib/devise/models/lockable.rb
@@ -1,3 +1,5 @@
require "devise/hooks/lockable"

module Devise
module Models
# Handles blocking a user access after a certain number of attempts.
Expand Down Expand Up @@ -89,8 +91,6 @@ def valid_for_authentication?
unlock_access! if lock_expired?

if super && !access_locked?
self.failed_attempts = 0
save(:validate => false)
true
else
self.failed_attempts ||= 0
Expand Down
13 changes: 13 additions & 0 deletions test/integration/recoverable_test.rb
Expand Up @@ -284,4 +284,17 @@ def reset_password(options={}, &block)
assert_current_url "/users/sign_in"
end
end

test "after recovering a password, should set failed attempts to 0" do
user = create_user
user.update_attribute(:failed_attempts, 10)

assert_equal 10, user.failed_attempts
request_forgot_password
reset_password :reset_password_token => user.reload.reset_password_token

assert warden.authenticated?(:user)
user.reload
assert_equal 0, user.failed_attempts
end
end
9 changes: 0 additions & 9 deletions test/models/lockable_test.rb
Expand Up @@ -14,15 +14,6 @@ def setup
end
end

test "should clear failed_attempts on successfull validation" do
user = create_user
user.confirm!
user.valid_for_authentication?{ false }
assert_equal 1, user.reload.failed_attempts
user.valid_for_authentication?{ true }
assert_equal 0, user.reload.failed_attempts
end

test "should increment failed_attempts on successfull validation if the user is already locked" do
user = create_user
user.confirm!
Expand Down

0 comments on commit e92ae37

Please sign in to comment.