How to lock users using Devise?

前端 未结 1 895
情深已故
情深已故 2021-01-04 11:24

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

1条回答
  •  臣服心动
    2021-01-04 11:46

    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!!

    0 讨论(0)
提交回复
热议问题