Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock users using Devise?

I want to add a subscription type functionality in my application for the account holder users such that with few failed login attempts they will not be able to access their account. Note: I don't want to delete their account from the database. I've already installed devise-2.1.2 in my application. Do any body have any idea how can it be done? I am newbie to Ruby on rails so it will be very helpful to me if you please explain the steps.

like image 656
Ahmad hamza Avatar asked Nov 01 '12 19:11

Ahmad hamza


People also ask

What is devise lock?

Overview. Handles blocking a user access after a certain number of attempts. Lockable accepts two different strategies to unlock a user after it's blocked: email and time. The former will send an email to the user when the lock happens, containing a link to unlock its account.

How do you unlock a devise account?

Devise will automatically unlock the user upon sign in if unlock_in period has passed.


1 Answers

Devise have a buil-in solution with the :lockable option check in the Devise Lockable Documentation

You have to set the lock_strategy set to :failed_attempts.

Step 1 Set your config/initializers/devise.rb to use:

# Defines which strategy will be used to lock an account.
config.lock_strategy = :failed_attempts

# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [ :time ]

# Defines which strategy will be used to unlock an account.
# :time  = Re-enables login after a certain amount of time (see :unlock_in below)
config.unlock_strategy = :time

# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
config.maximum_attempts = 3

# Time interval to unlock the account if :time is enabled as unlock_strategy.
config.unlock_in = 2.hours

Step 2 Your should add the lockable to you Model as this:

class Example < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, 
         :lockable

Step 3 Generate the migrations to make devise work

class AddLockableToExamples < ActiveRecord::Migration
  def change
    add_column :examples, :failed_attempts, :integer, default: 0
    add_column :examples, :unlock_token, :string
    add_column :examples, :locked_at, :datetime
  end
end

Regards!!

like image 160
felipeclopes Avatar answered Oct 05 '22 08:10

felipeclopes