Skip to content

Commit

Permalink
introducing lockable implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcelo Silveira committed Jan 1, 2010
1 parent 95989dc commit d2fa737
Show file tree
Hide file tree
Showing 26 changed files with 636 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rdoc
@@ -1,6 +1,7 @@
* enhancements
* Extract Activatable from Confirmable
* Decouple Serializers from Devise modules
* Devise::Lockable

== 0.7.3

Expand Down
3 changes: 3 additions & 0 deletions README.rdoc
Expand Up @@ -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 .

Expand Down Expand Up @@ -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

Expand All @@ -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:

Expand Down
33 changes: 33 additions & 0 deletions app/controllers/unlocks_controller.rb
@@ -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
4 changes: 4 additions & 0 deletions app/models/devise_mailer.rb
Expand Up @@ -22,6 +22,10 @@ def reset_password_instructions(record)
setup_mail(record, :reset_password_instructions)
end

def unlock_instructions(record)
setup_mail(record, :unlock_instructions)
end

private

# Configure default email options
Expand Down
7 changes: 7 additions & 0 deletions app/views/devise_mailer/unlock_instructions.html.erb
@@ -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) %>
4 changes: 4 additions & 0 deletions app/views/sessions/new.html.erb
Expand Up @@ -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 -%>
16 changes: 16 additions & 0 deletions app/views/unlocks/new.html.erb
@@ -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 -%>
1 change: 1 addition & 0 deletions generators/devise/templates/migration.rb
Expand Up @@ -6,6 +6,7 @@ def self.up
t.recoverable
t.rememberable
t.trackable
t.lockable

t.timestamps
end
Expand Down
14 changes: 13 additions & 1 deletion generators/devise_install/templates/devise.rb
Expand Up @@ -8,7 +8,7 @@
# 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.
Expand Down Expand Up @@ -54,6 +54,18 @@
# 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
Expand Down
20 changes: 17 additions & 3 deletions lib/devise.rb
Expand Up @@ -25,21 +25,22 @@ module Orm
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]
SERIALIZERS = [:session, :cookie]
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 = {
Expand Down Expand Up @@ -103,6 +104,19 @@ module Orm
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.
Expand Down
2 changes: 1 addition & 1 deletion lib/devise/controllers/url_helpers.rb
Expand Up @@ -19,7 +19,7 @@ module Controllers
# 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
Expand Down
7 changes: 5 additions & 2 deletions lib/devise/locales/en.yml
Expand Up @@ -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.'
Expand All @@ -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'
2 changes: 1 addition & 1 deletion lib/devise/models/activatable.rb
Expand Up @@ -5,7 +5,7 @@ module Models
# This module implements the default API required in activatable hook.
module Activatable
def active?
raise NotImplementedError
true
end

def inactive_message
Expand Down
8 changes: 6 additions & 2 deletions lib/devise/models/confirmable.rb
Expand Up @@ -76,12 +76,16 @@ def resend_confirmation!
# 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
Expand Down
138 changes: 138 additions & 0 deletions lib/devise/models/lockable.rb
@@ -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
2 changes: 2 additions & 0 deletions lib/devise/orm/active_record.rb
Expand Up @@ -7,6 +7,8 @@ module Orm
# t.confirmable
# t.recoverable
# t.rememberable
# t.trackable
# t.lockable
# t.timestamps
# end
#
Expand Down

0 comments on commit d2fa737

Please sign in to comment.