introducing lockable implementation

This commit is contained in:
Marcelo Silveira 2009-12-30 15:19:33 -02:00
parent 95989dc2a5
commit d2fa737aa0
26 changed files with 636 additions and 14 deletions

View File

@ -1,6 +1,7 @@
* enhancements
* Extract Activatable from Confirmable
* Decouple Serializers from Devise modules
* Devise::Lockable
== 0.7.3

View File

@ -17,6 +17,7 @@ Right now it's composed of seven mainly modules:
* Timeoutable: expires sessions without activity in a certain period of time.
* Trackable: tracks sign in count, timestamps and ip.
* Validatable: creates all needed validations for email and password. It's totally optional, so you're able to to customize validations by yourself.
* Lockable: takes care of locking an account based on the number of failed sign in attempts. Handles unlock via expire and email.
There's an example application using Devise at http://github.com/plataformatec/devise_example .
@ -62,6 +63,7 @@ We're assuming here you want a User model. First of all you have to setup a migr
t.confirmable
t.recoverable
t.rememberable
t.lockable
t.timestamps
end
@ -70,6 +72,7 @@ You may also want to add some indexes to improve performance:
add_index :your_table, :email
add_index :your_table, :confirmation_token # for confirmable
add_index :your_table, :reset_password_token # for recoverable
add_index :your_table, :unlock_token # for lockable
Now let's setup a User model adding the devise line to have your authentication working:

View File

@ -0,0 +1,33 @@
class UnlocksController < ApplicationController
include Devise::Controllers::Helpers
# GET /resource/unlock/new
def new
build_resource
render_with_scope :new
end
# POST /resource/unlock
def create
self.resource = resource_class.send_unlock_instructions(params[resource_name])
if resource.errors.empty?
set_flash_message :success, :send_instructions
redirect_to new_session_path(resource_name)
else
render_with_scope :new
end
end
# GET /resource/unlock?unlock_token=abcdef
def show
self.resource = resource_class.unlock!(:unlock_token => params[:unlock_token])
if resource.errors.empty?
set_flash_message :success, :unlocked
sign_in_and_redirect(resource_name, resource)
else
render_with_scope :new
end
end
end

View File

@ -22,6 +22,10 @@ class DeviseMailer < ::ActionMailer::Base
setup_mail(record, :reset_password_instructions)
end
def unlock_instructions(record)
setup_mail(record, :unlock_instructions)
end
private
# Configure default email options

View File

@ -0,0 +1,7 @@
Hello <%= @resource.email %>!
Your account has been locked due to an excessive amount of unsuccessful sign in attempts.
Click the link below to unlock your account:
<%= link_to 'Unlock my account', unlock_url(@resource, :unlock_token => @resource.unlock_token) %>

View File

@ -23,3 +23,7 @@
<%- if devise_mapping.confirmable? %>
<%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
<% end -%>
<%- if devise_mapping.lockable? %>
<%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br />
<% end -%>

View File

@ -0,0 +1,16 @@
<h2>Resend unlock instructions</h2>
<% form_for resource_name, resource, :url => unlock_path(resource_name) do |f| %>
<%= f.error_messages %>
<p><%= f.label :email %></p>
<p><%= f.text_field :email %></p>
<p><%= f.submit "Resend unlock instructions" %></p>
<% end %>
<%= link_to "Sign in", new_session_path(resource_name) %><br />
<%- if devise_mapping.recoverable? %>
<%= link_to "Forgot password?", new_password_path(resource_name) %><br />
<% end -%>

View File

@ -6,6 +6,7 @@ class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration
t.recoverable
t.rememberable
t.trackable
t.lockable
t.timestamps
end

View File

@ -8,7 +8,7 @@ Devise.setup do |config|
# Remember that Devise includes other modules on its own (like :activatable
# and :timeoutable) which are not included here and also plugins. So be sure
# to check the docs for a complete set.
config.all = [:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable]
config.all = [:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :lockable]
# Invoke `rake secret` and use the printed value to setup a pepper to generate
# the encrypted password. By default no pepper is used.
@ -54,6 +54,18 @@ Devise.setup do |config|
# are using only default views.
# config.scoped_views = true
# Number of authentication tries before locking an account.
# config.maximum_attempts = 5
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Reanables login after a certain ammount of time (see :unlock_in below)
# :both = enables both strategies
# config.unlock_strategy = :both
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# If you want to use other strategies, that are not (yet) supported by Devise,
# you can configure them inside the config.warden block. The example below
# allows you to setup OAuth, using http://github.com/roman/warden_oauth

View File

@ -25,13 +25,14 @@ module Devise
end
ALL = [:authenticatable, :activatable, :confirmable, :recoverable, :rememberable,
:timeoutable, :trackable, :validatable]
:timeoutable, :trackable, :validatable, :lockable]
# Maps controller names to devise modules
CONTROLLERS = {
:sessions => [:authenticatable],
:passwords => [:recoverable],
:confirmations => [:confirmable]
:confirmations => [:confirmable],
:unlocks => [:lockable]
}
STRATEGIES = [:authenticatable]
@ -39,7 +40,7 @@ module Devise
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
# Maps the messages types that are used in flash message.
FLASH_MESSAGES = [ :unauthenticated, :unconfirmed, :invalid, :timeout, :inactive ]
FLASH_MESSAGES = [ :unauthenticated, :unconfirmed, :invalid, :timeout, :inactive, :locked ]
# Declare encryptors length which are used in migrations.
ENCRYPTORS_LENGTH = {
@ -103,6 +104,19 @@ module Devise
mattr_accessor :scoped_views
@@scoped_views = false
# Number of authentication tries before locking an account
mattr_accessor :maximum_attempts
@@maximum_attempts = 5
# Defines which strategy can be used to unlock an account.
# Values: :email, :time, :both
mattr_accessor :unlock_strategy
@@unlock_strategy = :both
# Time interval to unlock the account if :time is defined as unlock_strategy.
mattr_accessor :unlock_in
@@unlock_in = 1.hour
class << self
# Default way to setup Devise. Run script/generate devise_install to create
# a fresh initializer with all configuration values.

View File

@ -19,7 +19,7 @@ module Devise
# Those helpers are added to your ApplicationController.
module UrlHelpers
[:session, :password, :confirmation].each do |module_name|
[:session, :password, :confirmation, :unlock].each do |module_name|
[:path, :url].each do |path_or_url|
actions = [ nil, :new_ ]
actions << :edit_ if module_name == :password

View File

@ -5,6 +5,7 @@ en:
signed_out: 'Signed out successfully.'
unauthenticated: 'You need to sign in or sign up before continuing.'
unconfirmed: 'You have to confirm your account before continuing.'
locked: 'Your account is locked.'
invalid: 'Invalid email or password.'
timeout: 'Your session expired, please sign in again to continue.'
inactive: 'Your account was not activated yet.'
@ -14,8 +15,10 @@ en:
confirmations:
send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.'
confirmed: 'Your account was successfully confirmed. You are now signed in.'
unlocks:
send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.'
unlocked: 'Your account was successfully unlocked. You are now signed in.'
mailer:
confirmation_instructions: 'Confirmation instructions'
reset_password_instructions: 'Reset password instructions'
unlock_instructions: 'Unlock Instructions'

View File

@ -5,7 +5,7 @@ module Devise
# This module implements the default API required in activatable hook.
module Activatable
def active?
raise NotImplementedError
true
end
def inactive_message

View File

@ -76,12 +76,16 @@ module Devise
# is already confirmed, it should never be blocked. Otherwise we need to
# calculate if the confirm time has not expired for this user.
def active?
confirmed? || confirmation_period_valid?
super && (confirmed? || confirmation_period_valid?)
end
# The message to be shown if the account is inactive.
def inactive_message
:unconfirmed
if !confirmed?
:unconfirmed
else
super
end
end
# If you don't want confirmation to be sent on create, neither a code

View File

@ -0,0 +1,138 @@
require 'devise/models/activatable'
module Devise
module Models
module Lockable
include Devise::Models::Activatable
include Devise::Models::Authenticatable
def self.included(base)
base.class_eval do
extend ClassMethods
end
end
# Lock an user setting it's locked_at to actual time.
def lock!
self.locked_at = Time.now
if [:both, :email].include?(self.class.unlock_strategy)
generate_unlock_token
self.send_unlock_instructions
end
save(false)
end
# Unlock an user by cleaning locket_at and failed_attempts
def unlock!
if_locked do
self.locked_at = nil
self.failed_attempts = 0
self.unlock_token = nil
save(false)
end
end
# Verifies whether a user is locked or not
def locked?
self.locked_at && !lock_expired?
end
# Send unlock instructions by email
def send_unlock_instructions
::DeviseMailer.deliver_unlock_instructions(self)
end
# Resend the unlock instructions if the user is locked
def resend_unlock!
if_locked do
generate_unlock_token unless self.unlock_token.present?
save(false)
send_unlock_instructions
end
end
# Overwrites active? from Devise::Models::Activatable for locking purposes
# by verifying whether an user is active to sign in or not based on locked?
def active?
super && !locked?
end
# Overwrites valid_for_authentication? from Devise::Models::Authenticatable
# for verifying whether an user is allowed to sign in or not. If the user
# is locked, it should never be allowed.
def valid_for_authentication?(attributes)
unless result = super
self.failed_attempts += 1
save(false)
self.lock! if self.failed_attempts > self.class.maximum_attempts
else
self.failed_attempts = 0
save(false)
end
result
end
# Overwrites invalid_message from Devise::Models::Authenticatable to define
# the correct reason for blocking the sign in.
def inactive_message
if locked?
:locked
else
super
end
end
protected
# Generates unlock token
def generate_unlock_token
self.unlock_token = Devise.friendly_token
end
# Tells if the lock is expired if :time unlock strategy is active
def lock_expired?
if [:both, :time].include?(self.class.unlock_strategy)
self.locked_at && self.locked_at < self.class.unlock_in.ago
else
false
end
end
# Checks whether the record is locked or not, yielding to the block
# if it's locked, otherwise adds an error to email.
def if_locked
if locked?
yield
else
self.class.add_error_on(self, :email, :not_locked)
false
end
end
module ClassMethods
# Attempt to find a user by it's email. If a record is found, send new
# unlock instructions to it. If not user is found, returns a new user
# with an email not found error.
# Options must contain the user email
def send_unlock_instructions(attributes={})
lockable = find_or_initialize_with_error_by(:email, attributes[:email], :not_found)
lockable.resend_unlock! unless lockable.new_record?
lockable
end
# Find a user by it's unlock token and try to unlock it.
# If no user is found, returns a new user with an error.
# If the user is not locked, creates an error for the user
# Options must have the unlock_token
def unlock!(attributes={})
lockable = find_or_initialize_with_error_by(:unlock_token, attributes[:unlock_token])
lockable.unlock! unless lockable.new_record?
lockable
end
Devise::Models.config(self, :maximum_attempts, :unlock_strategy, :unlock_in)
end
end
end
end

View File

@ -7,6 +7,8 @@ module Devise
# t.confirmable
# t.recoverable
# t.rememberable
# t.trackable
# t.lockable
# t.timestamps
# end
#

View File

@ -113,6 +113,10 @@ module ActionController::Routing
routes.resource :confirmation, :only => [:new, :create, :show], :as => mapping.path_names[:confirmation]
end
def lockable(routes, mapping)
routes.resource :unlock, :only => [:new, :create, :show], :as => mapping.path_names[:unlock]
end
end
end
end

View File

@ -45,6 +45,13 @@ module Devise
apply_schema :last_sign_in_ip, String
end
# Creates failed_attempts, unlock_token and locked_at
def lockable
apply_schema :failed_attempts, Integer, :default => 0
apply_schema :unlock_token, String, :limit => 20
apply_schema :locked_at, DateTime
end
# Overwrite with specific modification to create your own schema.
def apply_schema(name, type, options={})
raise NotImplementedError

View File

@ -0,0 +1,83 @@
require 'test/test_helper'
class LockTest < ActionController::IntegrationTest
def visit_user_unlock_with_token(unlock_token)
visit user_unlock_path(:unlock_token => unlock_token)
end
test 'user should be able to request a new unlock token' do
user = create_user(:locked => true)
ActionMailer::Base.deliveries.clear
visit new_user_session_path
click_link 'Didn\'t receive unlock instructions?'
fill_in 'email', :with => user.email
click_button 'Resend unlock instructions'
assert_template 'sessions/new'
assert_contain 'You will receive an email with instructions about how to unlock your account in a few minutes'
assert_equal 1, ActionMailer::Base.deliveries.size
end
test 'unlocked user should not be able to request a unlock token' do
user = create_user(:locked => false)
ActionMailer::Base.deliveries.clear
visit new_user_session_path
click_link 'Didn\'t receive unlock instructions?'
fill_in 'email', :with => user.email
click_button 'Resend unlock instructions'
assert_template 'unlocks/new'
assert_contain 'not locked'
assert_equal 0, ActionMailer::Base.deliveries.size
end
test 'user with invalid unlock token should not be able to unlock an account' do
visit_user_unlock_with_token('invalid_token')
assert_response :success
assert_template 'unlocks/new'
assert_have_selector '#errorExplanation'
assert_contain /Unlock token(.*)invalid/
end
test "locked user should be able to unlock account" do
user = create_user(:locked => true)
assert user.locked?
visit_user_unlock_with_token(user.unlock_token)
assert_template 'home/index'
assert_contain 'Your account was successfully unlocked.'
assert_not user.reload.locked?
end
test "sign in user automatically after unlocking it's account" do
user = create_user(:locked => true)
visit_user_unlock_with_token(user.unlock_token)
assert warden.authenticated?(:user)
end
test "user should not be able to sign in when locked" do
user = sign_in_as_user(:locked => true)
assert_template 'sessions/new'
assert_contain 'Your account is locked.'
assert_not warden.authenticated?(:user)
end
test 'error message is configurable by resource name' do
store_translations :en, :devise => {
:sessions => { :admin => { :locked => "You are locked!" } }
} do
get new_admin_session_path(:locked => true)
assert_contain 'You are locked!'
end
end
end

View File

@ -0,0 +1,62 @@
require 'test/test_helper'
class UnlockInstructionsTest < ActionMailer::TestCase
def setup
setup_mailer
DeviseMailer.sender = 'test@example.com'
end
def user
@user ||= begin
user = create_user
user.lock!
user
end
end
def mail
@mail ||= begin
user
ActionMailer::Base.deliveries.last
end
end
test 'email sent after locking the user' do
assert_not_nil mail
end
test 'content type should be set to html' do
assert_equal 'text/html', mail.content_type
end
test 'send unlock instructions to the user email' do
assert_equal [user.email], mail.to
end
test 'setup sender from configuration' do
assert_equal ['test@example.com'], mail.from
end
test 'setup subject from I18n' do
store_translations :en, :devise => { :mailer => { :unlock_instructions => 'Unlock instructions' } } do
assert_equal 'Unlock instructions', mail.subject
end
end
test 'subject namespaced by model' do
store_translations :en, :devise => { :mailer => { :user => { :unlock_instructions => 'User Unlock Instructions' } } } do
assert_equal 'User Unlock Instructions', mail.subject
end
end
test 'body should have user info' do
assert_match /#{user.email}/, mail.body
end
test 'body should have link to unlock the account' do
host = ActionMailer::Base.default_url_options[:host]
unlock_url_regexp = %r{<a href=\"http://#{host}/users/unlock\?unlock_token=#{user.unlock_token}">}
assert_match unlock_url_regexp, mail.body
end
end

View File

@ -0,0 +1,202 @@
require 'test/test_helper'
class LockableTest < ActiveSupport::TestCase
def setup
setup_mailer
end
test "should increment failed attempts on unsuccessful authentication" do
user = create_user
assert_equal 0, user.failed_attempts
authenticated_user = User.authenticate(:email => user.email, :password => "anotherpassword")
assert_equal 1, user.reload.failed_attempts
end
test "should lock account base on maximum_attempts" do
user = create_user
attempts = Devise.maximum_attempts + 1
attempts.times { authenticated_user = User.authenticate(:email => user.email, :password => "anotherpassword") }
assert user.reload.locked?
end
test "should respect maximum attempts configuration" do
user = create_user
swap Devise, :maximum_attempts => 2 do
3.times { authenticated_user = User.authenticate(:email => user.email, :password => "anotherpassword") }
assert user.reload.locked?
end
end
test "should clear failed_attempts on successfull sign in" do
user = create_user
User.authenticate(:email => user.email, :password => "anotherpassword")
assert_equal 1, user.reload.failed_attempts
User.authenticate(:email => user.email, :password => "123456")
assert_equal 0, user.reload.failed_attempts
end
test "should verify wheter a user is locked or not" do
user = create_user
assert_not user.locked?
user.lock!
assert user.locked?
end
test "active? should be the opposite of locked?" do
user = create_user
user.confirm!
assert user.active?
user.lock!
assert_not user.active?
end
test "should unlock an user by cleaning locked_at, falied_attempts and unlock_token" do
user = create_user
user.lock!
assert_not_nil user.reload.locked_at
assert_not_nil user.reload.unlock_token
user.unlock!
assert_nil user.reload.locked_at
assert_nil user.reload.unlock_token
assert 0, user.reload.failed_attempts
end
test 'should not unlcok an unlocked user' do
user = create_user
assert_not user.unlock!
assert_match /not locked/, user.errors[:email]
end
test "new user should not be locked and should have zero failed_attempts" do
assert_not new_user.locked?
assert_equal 0, create_user.failed_attempts
end
test "should unlock user after unlock_in period" do
swap Devise, :unlock_in => 3.hours do
user = new_user
user.locked_at = 2.hours.ago
assert user.locked?
Devise.unlock_in = 1.hour
assert_not user.locked?
end
end
test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do
swap Devise, :unlock_strategy => :email do
user = new_user
user.locked_at = 2.hours.ago
assert user.locked?
end
end
test "should set unlock_token when locking" do
user = create_user
assert_nil user.unlock_token
user.lock!
assert_not_nil user.unlock_token
end
test 'should not regenerate unlock token if it already exists' do
user = create_user
user.lock!
3.times do
token = user.unlock_token
user.resend_unlock!
assert_equal token, user.unlock_token
end
end
test "should never generate the same unlock token for different users" do
unlock_tokens = []
3.times do
user = create_user
user.lock!
token = user.unlock_token
assert !unlock_tokens.include?(token)
unlock_tokens << token
end
end
test "should not generate unlock_token when :email is not an unlock strategy" do
swap Devise, :unlock_strategy => :time do
user = create_user
user.lock!
assert_nil user.unlock_token
end
end
test "should send email with unlock instructions when :email is an unlock strategy" do
swap Devise, :unlock_strategy => :email do
user = create_user
assert_email_sent do
user.lock!
end
end
end
test "should not send email with unlock instructions when :email is not an unlock strategy" do
swap Devise, :unlock_strategy => :time do
user = create_user
assert_email_not_sent do
user.lock!
end
end
end
test 'should find and unlock an user automatically' do
user = create_user
user.lock!
locked_user = User.unlock!(:unlock_token => user.unlock_token)
assert_equal locked_user, user
assert_not user.reload.locked?
end
test 'should return a new record with errors when a invalid token is given' do
locked_user = User.unlock!(:unlock_token => 'invalid_token')
assert locked_user.new_record?
assert_match /invalid/, locked_user.errors[:unlock_token]
end
test 'should return a new record with errors when a blank token is given' do
locked_user = User.unlock!(:unlock_token => '')
assert locked_user.new_record?
assert_match /blank/, locked_user.errors[:unlock_token]
end
test 'should authenticate a unlocked user' do
user = create_user
user.lock!
user.unlock!
authenticated_user = User.authenticate(:email => user.email, :password => user.password)
assert_equal authenticated_user, user
end
test 'should find a user to send unlock instructions' do
user = create_user
user.lock!
unlock_user = User.send_unlock_instructions(:email => user.email)
assert_equal unlock_user, user
end
test 'should return a new user if no email was found' do
unlock_user = User.send_unlock_instructions(:email => "invalid@email.com")
assert unlock_user.new_record?
end
test 'should add error to new user email if no email was found' do
unlock_user = User.send_unlock_instructions(:email => "invalid@email.com")
assert unlock_user.errors[:email]
assert_equal 'not found', unlock_user.errors[:email]
end
test 'should not be able to send instructions if the user is not locked' do
user = create_user
assert_not user.resend_unlock!
assert_not user.locked?
assert_equal 'not locked', user.errors[:email]
end
end

View File

@ -24,6 +24,10 @@ class Timeoutable < User
devise :authenticatable, :timeoutable
end
class Lockable < User
devise :authenticatable, :lockable
end
class IsValidatable < User
devise :authenticatable, :validatable
end
@ -33,7 +37,7 @@ class Devisable < User
end
class Exceptable < User
devise :all, :except => [:recoverable, :rememberable, :validatable]
devise :all, :except => [:recoverable, :rememberable, :validatable, :lockable]
end
class Configurable < User
@ -84,13 +88,17 @@ class ActiveRecordTest < ActiveSupport::TestCase
assert_include_modules Timeoutable, :authenticatable, :timeoutable
end
test 'add lockable module only' do
assert_include_modules Lockable, :authenticatable, :lockable
end
test 'add validatable module only' do
assert_include_modules IsValidatable, :authenticatable, :validatable
end
test 'add all modules' do
assert_include_modules Devisable,
:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable
:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :lockable
end
test 'configure modules with except option' do

View File

@ -16,6 +16,7 @@ ActiveRecord::Schema.define(:version => 1) do
t.recoverable
t.rememberable
t.trackable
t.lockable
end
t.timestamps

View File

@ -1,5 +1,5 @@
class Admin < ActiveRecord::Base
devise :all, :timeoutable, :except => [:recoverable, :confirmable, :rememberable, :validatable, :trackable]
devise :all, :timeoutable, :except => [:recoverable, :confirmable, :rememberable, :validatable, :trackable, :lockable]
def self.find_for_authentication(conditions)
last(:conditions => conditions)

View File

@ -8,7 +8,7 @@ Devise.setup do |config|
# Remember that Devise includes other modules on its own (like :activatable
# and :timeoutable) which are not included here and also plugins. So be sure
# to check the docs for a complete set.
config.all = [:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable]
config.all = [:authenticatable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :lockable]
# Invoke `rake secret` and use the printed value to setup a pepper to generate
# the encrypted password. By default no pepper is used.
@ -54,6 +54,18 @@ Devise.setup do |config|
# are using only default views.
# config.scoped_views = true
# Number of authentication tries before locking an account.
# config.maximum_attempts = 5
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Reanables login after a certain ammount of time (see :unlock_in below)
# :both = enables both strategies
# config.unlock_strategy = :both
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# If you want to use other strategies, that are not (yet) supported by Devise,
# you can configure them inside the config.warden block. The example below
# allows you to setup OAuth, using http://github.com/roman/warden_oauth

View File

@ -10,6 +10,7 @@ class ActionController::IntegrationTest
:email => 'user@test.com', :password => '123456', :password_confirmation => '123456', :created_at => Time.now.utc
)
user.confirm! unless options[:confirm] == false
user.lock! if options[:locked] == true
user
end
end