I'm using Devise 3.5.2 for authentication with the devise_ldap_authenticable gem on Rails 4.2.4. I've moved from the released 0.8.5 gem to the github master level (0.8.6).
From what I can tell, the LDAP plugin authentication code is not running. It's not writing any log messages.
I previously got regular database authentication to work for this application. I'm now trying to get LDAP authentication to work.
For example:
Started POST "/users/sign_in" for ::1 at 2015-11-23 16:05:14 -0500
ActiveRecord::SchemaMigration Load (87.6ms) SELECT schema_migrations.* FROM schema_migrations
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Mos...w==", "user"=>{"login"=>"leonsp", "password"=>"...", "remember_me"=>"0"}}
Completed 401 Unauthorized in 95ms (ActiveRecord: 0.0ms)
There should be LDAP log messages in there.
My user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
#
# :database_authenticable is not enabled
devise :ldap_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :zxcvbnable
attr_accessible :email, :userid, :shortuserid, :login # etc...
# Virtual attribute for authenticating by either userid or email
# This is in addition to a real persisted field like 'userid'
attr_accessor :login
# ...
def self.find_for_database_authentication(warden_conditions)
Rails.logger.debug "Finding for database authentication"
conditions = warden_conditions.dup
login = conditions.delete(:login).try(:downcase)
if login.present?
Rails.logger.debug "Finding by login #{login}"
where(conditions.to_hash).find_by([
"lower(userid) = :value OR lower(shortuserid) = :value OR lower(email) = :value", { value: login }
])
else
Rails.logger.debug "Finding by conditions #{login}"
find_by(conditions.to_hash)
end
end
def self.find_for_ldap_authentication(warden_conditions)
Rails.logger.debug "Finding for ldap authentication"
conditions = warden_conditions.dup
login = conditions.delete(:login).try(:downcase)
if login.present?
Rails.logger.debug "Finding by login #{login}"
if login.include? "#"
conditions[:email] = login
super conditions
else
conditions[:userid] = login
super conditions
end
else
Rails.logger.debug "No login. Using default behaviour"
super
end
end
# ...
Here's the initializer for Devise. I added the monkeypatch at the front while debugging:
module Devise
module Strategies
class LdapAuthenticatable < Authenticatable
def authenticate!
Rails.logger.debug "=== Starting LDAP Authentication ==="
super
Rails.logger.debug "=== Done LDAP Authentication ==="
end
end
end
end
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# TODO: https://github.com/cschiewek/devise_ldap_authenticatable/issues/153
# ==> LDAP Configuration
# config.ldap_logger = true
# config.ldap_create_user = false
# config.ldap_update_password = true
# config.ldap_config = "#{Rails.root}/config/ldap.yml"
# config.ldap_check_group_membership = false
# config.ldap_check_group_membership_without_admin = false
# config.ldap_check_attributes = false
# config.ldap_use_admin_to_bind = false
# config.ldap_ad_group_check = false
config.ldap_logger = true
config.ldap_create_user = true
config.ldap_update_password = true
config.ldap_use_admin_to_bind = true
config.ldap_auth_username_builder = proc do |attribute, login, ldap|
username_string = "#{attribute}=#{login},#{ldap.base}"
Rails.logger.debug "Generated username as #{username_string}"
username_string
end
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [:login, :email, :userid]
# ...
I can successfully connect to the LDAP server on the machine using ldapsearch:
ldapsearch -x -W -D "cn=admin,dc=my_domain,dc=com" -H ldap://my_hostname.my_domain.com "(cn=leonsp)"
Here's the corresponding configuration the ldap.yml:
## Authorizations
# Uncomment out the merging for each environment that you'd like to include.
# You can also just copy and paste the tree (do not include the "authorizations") to each
# environment if you need something different per environment.
authorizations: &AUTHORIZATIONS
allow_unauthenticated_bind: false
group_base: ou=groups,dc=my_domain,dc=com
## Requires config.ldap_check_group_membership in devise.rb be true
# Can have multiple values, must match all to be authorized
required_groups:
## Requires config.ldap_check_attributes in devise.rb to be true
## Can have multiple attributes and values, must match all to be authorized
require_attribute:
objectClass: inetOrgPerson
## Environment
development:
host: ldap://my_hostname.my_domain.com
port: 389
attribute: cn
base: dc=my_domain,dc=com
admin_user: cn=admin,dc=my_domain,dc=com
admin_password: ...
ssl: none
# <<: *AUTHORIZATIONS
Am I correct in assuming that the LDAP plugin code for Devise is not running?
Why isn't it running?
Why aren't any of my debug statements being reached?
What additional methods can I monkeypatch with debug statements to debug the issue?
What other diagnostics can I collect?
Edit: I'm tracing the execution using the byebug debugger. So far I can tell that :ldap_authenticable shows up on the list of strategies during sign in, but doesn't seem to result in any :ldap_authenticable-specific code execution.
The main issue was that I had included optional parameters in config.authentication_keys. This made Devise::Strategies#parse_authentication_key_values fail silently. Only mandatory parameters should be included in authentication_keys.
Other issues related to the application being designed to allow users to log in with either their username or their email address. To allow for users to log in using either, I had to:
Override login_with in the User model
Override self.find_for_ldap_authentication in the User model
Rename the fake attr_accessor :login to attr_accessor :username in order to better distinguish it from the different meaning of :login in the gem
One last issue: Don't include protocol (e.g. ldaps://) in the host attributes of ldap.yml
For those coming to this thread still, I was able to get it to work by dropping down to gem version 0.8.4.
Related
My application authentication is based on Devise. My customer now requires more security with passwords and registration emails management, so I installed the devise-security gem. As recommended in the E-Mail Validation topic of the wiki, I also added the email_address gem.
Here is the Gemfile:
# Authentication and Authorisations
gem 'devise'
gem 'devise-security'
gem 'email_address' # for email validation
gem 'cancancan', '~> 3.0'
The User model contains:
class User < ApplicationRecord
extend CsvHelper
validates_with EmailAddress::ActiveRecordValidator, field: :email
# Virtual attribute for authenticating by either username or email
# This is in addition to a real persisted field like 'username'
attr_accessor :login
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :secure_validatable, :confirmable, :lockable, :password_archivable
### validations
#validates :email, :presence => true, :email => true
config/initializers/devise.rb contains:
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# config.secret_key = 'a49a0d923cf906a896ff86cc42273cd1cfb578a6f3123173f7631c51b0ed8eea6233a0fc832d1dc1ea733b6f1f5e31b25d4c8d670641a64af76dad8690f00bf2'
# ==> Mailer Configuration
config.mailer_sender = 'SIS#bfs.admin.ch'
# Configure the class responsible to send e-mails.
config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
config.authentication_keys = [:login]
# Configure parameters from the request object used for authentication.
config.request_keys = []
# Configure which authentication keys should be case-insensitive.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
config.strip_whitespace_keys = [:email]
# By default Devise will store the user in session.
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
config.stretches = Rails.env.test? ? 1 : 11
# Send a notification to the original email when the user's email is changed.
config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
config.send_password_change_notification = false
# ==> Configuration for :confirmable
config.confirm_within = 1.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied.
config.reconfirmable = true
# Defines which key will be used when confirming an account
config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
config.remember_for = 1.days
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = false
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats.
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
# ==> Configuration for :lockable
config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
config.unlock_strategy = :email
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
config.maximum_attempts = 3
# Warn on the last attempt before the account is locked.
config.last_attempt_warning = true
# ==> Configuration for :recoverable
# Time interval you can reset your password with a reset password key.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset.
config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# config.encryptor = :sha512
# ==> Scopes configuration
# config.scoped_views = false
# Configure the default scope given to Warden..
# config.default_scope = :user
# ==> Navigation configuration
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
end
config/initializers/devise-security.rb contains:
Devise.setup do |config|
# ==> Security Extension
# Configure security extension for devise
# Should the password expire (e.g 3.months)
config.expire_password_after = 1.year
# Need 1 char of A-Z, a-z and 0-9
config.password_complexity = { digit: 1, lower: 1, symbol: 1, upper: 1 }
# How many passwords to keep in archive
config.password_archiving_count = 10
# Deny old passwords (true, false, number_of_old_passwords_to_check)
# Examples:
# config.deny_old_passwords = false # allow old passwords
# config.deny_old_passwords = true # will deny all the old passwords
# config.deny_old_passwords = 3 # will deny new passwords that matches with the last 3 passwords
config.deny_old_passwords = true
# enable email validation for :secure_validatable. (true, false, validation_options)
# dependency: see https://github.com/devise-security/devise-security/blob/master/README.md#e-mail-validation
config.email_validation = true
end
Since I add :secure_validatable, the Puma server refuses to start and raises the following error:
C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/activemodel-5.2.4.2/lib/active_model/validations/validates.rb:121:in
`rescue in block in validates': Unknown validator: 'EmailValidator'
(ArgumentError)
What did I miss with configuration of this validation feature?
Thanks for your help!
Please add email_validation: false to user.rb as:
`
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :secure_validatable, :confirmable, :lockable, :password_archivable, email_validation: false
`
Here is the answer, which we all need to know.
We don't need to mention email_validation: false as it will not validate emails and password for secure_validatable if the value would be false
Your Model class should look like this -> app/model/user.rb.
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :secure_validatable
Be sure, no other format validation should be there for an email in user.rb. Eg:
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP}
Other than the format validation is okay to have. Eg:
validates :email, presence: { message: "Email can't be blank" }, uniqueness: { message: "This email is already registered with us. Please check again and puts your email address." }
Now the real game begins, you have to create a new validator file -> app/validators/email_validator.rb
NOTE - Don't change the function name validate in EmailValidator class, although you can change the inner functionality according to you.
require 'uri'
class EmailValidator < ActiveModel::Validator
def validate(record)
if record.email.match? URI::MailTo::EMAIL_REGEXP
return
else
raise ActiveRecord::Rollback
record.errors[:email] << 'has an invalid format'
end
end
end
Also, now you can comment out the line from config/initializers/devise.rb, as now it's not using this email regex config anymore from devise.
# config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
The config/initializers/devise_security.rb should look like the below to use secure_validatable properly.
NOTE
You don't need to worry about the config.email_validation to be true as it's default value in devise_security gem is true
Also, you don't need to worry for config.password_complexity = { digit: 1, lower: 1, symbol: 1, upper: 1 } as the default complexity already sets the value 1 for everything.
# frozen_string_literal: true
Devise.setup do |config|
# ==> Security Extension
# Configure security extension for devise
# Should the password expire (e.g 3.months)
# config.expire_password_after = false
# Need 1 char each of: A-Z, a-z, 0-9, and a punctuation mark or symbol
# You may use "digits" in place of "digit" and "symbols" in place of
# "symbol" based on your preference
config.password_complexity = { digit: 1, lower: 1, symbol: 1, upper: 1 }
# How many passwords to keep in archive
# config.password_archiving_count = 5
# Deny old passwords (true, false, number_of_old_passwords_to_check)
# Examples:
# config.deny_old_passwords = false # allow old passwords
# config.deny_old_passwords = true # will deny all the old passwords
# config.deny_old_passwords = 3 # will deny new passwords that matches with the last 3 passwords
# config.deny_old_passwords = true
# enable email validation for :secure_validatable. (true, false, validation_options)
# dependency: see https://github.com/devise-security/devise-security/blob/master/README.md#e-mail-validation
# config.email_validation = true
# captcha integration for recover form
# config.captcha_for_recover = true
# captcha integration for sign up form
# config.captcha_for_sign_up = true
# captcha integration for sign in form
# config.captcha_for_sign_in = true
# captcha integration for unlock form
# config.captcha_for_unlock = true
# captcha integration for confirmation form
# config.captcha_for_confirmation = true
# Time period for account expiry from last_activity_at
# config.expire_after = 90.days
# Allow password to equal the email
# config.allow_passwords_equal_to_email = false
end
🎉 The code is perfectly fine now to use the secure_validatable for your model.
Reference of my answer - https://github.com/devise-security/devise-security/issues/77#issuecomment-1405101158
I'm building an app with Rails 4.1.4, Mongoid 4.0.0 and Devise 3.3.0 (Warden 1.2.3) for authentication.
Everything about authentication with Devise is working well (sign up, sign in, confirmation, password recovery, etc.). The issue I'm having is that when I sign in, although it says that sign in was successful, and in the database the sign_in_count increases and last_sign_in_at updates, the user session is not being stored in the cookies, namely the helpers user_signed_in?, user_session, current_user, etc. are not working.
I actually have two distinct models that work with authentication, one named Customer and one named Admin. So my helpers are customer_* or *_customer, and admin_* or *_admin respectively. None of them working.
These are my models...
customer.rb
class Customer
include Mongoid::Document
include Mongoid::Timestamps
# Include default devise modules. Others available are:
# :token_authenticatable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Database authenticatable
field :email, type: String
field :encrypted_password, type: String
validates_presence_of :email
validates_presence_of :encrypted_password
# Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
# Rememberable
field :remember_created_at, type: Time
# Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
# Confirmable
field :confirmation_token, type: String
field :confirmed_at, type: Time
field :confirmation_sent_at, type: Time
field :unconfirmed_email, type: String # Only if using reconfirmable
# Lockable
# field :failed_attempts, :type => Integer, :default => 0 # Only if lock strategy is :failed_attempts
# field :unlock_token, :type => String # Only if unlock strategy is :email or :both
# field :locked_at, :type => Time
# Token authenticatable
# field :authentication_token, :type => String
# Run 'rake db:mongoid:create_indexes' to create indexes
index({ email: 1 }, { unique: true, background: true })
# Extra data.
field :first_name, type: String
field :last_name, type: String
validates_presence_of :first_name
validates_presence_of :last_name
# Devise serializing problem fix.
class << self
def serialize_from_session(key,salt)
record = to_adapter.get(key[0].to_param)
record if record && record.authenticatable_salt == salt
end
end
end
admin.rb
class Admin
include Mongoid::Document
include Mongoid::Timestamps
devise :database_authenticatable, :timeoutable, :lockable
# Database authenticatable
field :email, type: String
field :encrypted_password, type: String
validates_presence_of :email
validates_presence_of :encrypted_password
# Lockable
field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
field :unlock_token, type: String # Only if unlock strategy is :email or :both
field :locked_at, type: Time
# Run 'rake db:mongoid:create_indexes' to create indexes
index({ email: 1 }, { unique: true, background: true })
# Extra data.
field :is_admin, type: Boolean, default: false
field :is_editor, type: Boolean, default: true
# Devise serializing problem fix.
class << self
def serialize_from_session(key,salt)
record = to_adapter.get(key[0].to_param)
record if record && record.authenticatable_salt == salt
end
end
end
And my initializer just in case...
devise.rb
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = <secret_key>
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = <mailer_sender>
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/mongoid'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
config.params_authenticatable = [:database]
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
config.pepper = <pepper>
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
config.rememberable_options = { secure: true }
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^#]+#[^#]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
config.scoped_views = true
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
Any hint to fix this problem?. Would really appreciate it!. Best,
UPDATE!!!
I'm adding here some more code for further information...
application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_locale
before_filter :authenticate_customer!
before_filter :authenticate_admin!
# Set locale according to locale parameter.
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
# Set actual locale value to be the default locale parameter.
def default_url_options(options={})
{ locale: I18n.locale }
end
# Configure permitted parameters for devise.
protected
def devise_parameter_sanitizer
if resource_class == Customer
Customer::ParameterSanitizer.new(Customer, :customer, params)
else
super # Use the default one
end
end
end
welcome_controller.rb (my one and only controller for now)
class WelcomeController < ApplicationController
skip_before_action :authenticate_customer!
skip_before_action :authenticate_admin!
before_filter :require_admin_not_signed_in
before_filter :require_customer_not_signed_in
def home
end
private
# Add filter to skip home page if customer is already signed in.
def require_customer_not_signed_in
unless not customer_signed_in?
redirect_to member_dashboard_path
end
end
# Add filter to skip home page if admin is already signed in.
def require_admin_not_signed_in
unless not admin_signed_in?
redirect_to admin_dashboard_path
end
end
end
SOLVED!!!
In my models I was adding a fix for a session serializing problem in Devise. This fix was causing the issue. This is the fix I'm talking about:
.
.
.
# Devise serializing problem fix.
class << self
def serialize_from_session(key,salt)
record = to_adapter.get(key[0].to_param)
record if record && record.authenticatable_salt == salt
end
end
.
.
.
I've changed that to this:
.
.
.
# Devise serializing problem fix.
class << self
def serialize_from_session(key, salt)
record = to_adapter.get(key[0]["$oid"])
record if record && record.authenticatable_salt == salt
end
end
.
.
.
And now it all works!.
Regards,
Your settings look correct and the issue isn't in your modules else sign in etc would not be working.
I would personally go through the following:
Ensure before_filter :authenticate_< scope >! is on your ApplicationController (swap out scope for user etc). Then use a skip_before_filter on the controllers you dont want protected
Ensure you are not attempting to access current_user etc from a controller action that is skipping the authenticate_user filter
All correct? Try patching your own SessionController if you havnt already ie. Devise::SessionsController and manually overwrite methods and test with trial and error.
Would i be able to see your Application and session controllers?
I was facing a similar problem with Devise and Mongoid.
I came to another solution, which also improves the session object by keeping it simple (it will store a string instead of BSON::Object)[1]
class User
# ...
# Serialize string instead of BSON
def self.serialize_into_session(record)
[record.to_key.map(&:to_s), record.authenticatable_salt]
end
# Serialize string instead of BSON
def self.serialize_into_cookie(record)
[record.to_key.map(&:to_s), record.rememberable_value]
end
# ...
end
Be aware of "serialize into cookie" because it is as important as serialize_into_session if you are using the remember me feature
[1] https://github.com/NoamB/sorcery/issues/405#issue-10811843
I have a Rails 4 Ecommerce app, and I'm using Devise for user authentication.
I'm also using ActiveAdmin, which uses Devise for it's authentication as well.
The issue I'm running into is that I'm getting logged out at random times. It almost seems like the session is being clobbered, but the session cookie stays the same. I tried removing the Devise skip_session_storage option, but no dice.
I'm storing sessions in memcached using :dalli_store.
My devise.rb looks like:
# require 'devise-encryptable'
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = '<secret_key>'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
# TODO:
config.mailer_sender = 'noreply#example.com'
# Configure the class responsible to send e-mails.
config.mailer = 'Store::UserMailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
config.http_authenticatable_on_xhr = false
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
# config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
config.pepper = '<pepper_value>'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = false
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^#]+#[^#]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
config.sign_out_all_scopes = false
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
config.navigational_formats = ['*/*', :json, :html]
DeviseController.respond_to :html, :json
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
config.warden do |manager|
manager.failure_app = ::FailureApp
end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :store
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
And the User.rb:
module Store
class User < DataModels::User
devise :confirmable, :rememberable, :async, :database_authenticatable, :registerable,
:recoverable, :validatable
validates :firstname,
:lastname,
presence: true,
allow_blank: false,
allow_nil: false
belongs_to :group, touch: true
belongs_to :shipping, class_name: "Address"
belongs_to :billing, class_name: "Address"
has_many :sales, as: :saleable
has_many :orders
# Rest removed for brevity
end
end
Any pointers? I've spent all day googling and digging into Devise and Warden's source code, to no avail.
We never did figure out what exactly was the issue, but I'm guessing memcached was sweeping up the sessions for some reason.
We switched to storing sessions in the DB, and we haven't seen this issue since.
Few things:
What version of ActiveAdmin are you using?
What does the :async devise option do?
What is the source of your Warden ::FailureApp?
Are you sure that it is actually Devise logging you out and not ActiveAdmin not authorizing you for an action via CanCan, or your own custom :authorization_adapter? Seems unlikely that this would be intermittent, but would be easy to check by configuring AA to use your own method in an ApplicationController so you can inspect the exception, current user and all that via Pry when it does occur.
I just created a new user for my admin controller in the rails console. I restart my app, enter my credentials and then I get the following message:
NameError in Devise::SessionsController#create
undefined local variable or method `locked_at' for #<Admin:0x4f289e8>
Rails.root: C:/rails_projects/my_blog-master
Application Trace | Framework Trace | Full Trace
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"OKFwtFvHFqQ8fUkppNc5wSxnr8ynaIccz7MQnTNdgrw=",
"admin"=>{"email"=>"geo.offley#gmail.com",
"password"=>"[FILTERED]"},
"commit"=>"Sign in"}
Show session dump
Show env dump
Response
Headers:
None
Not entirely sure why it's doing it, from what I can gather it's having issues creating a new session for my app, but I don't know how I would fix this.
Any help would be appreciated!!
Update!!
Here is my admin.rb file
class Admin < ActiveRecord::Base
devise :database_authenticatable, :trackable, :timeoutable, :lockable
attr_accessible :email, :password, :password_confirmation, :lockable
end
And here is the migration I created:
class DeviseCreateAdmins < ActiveRecord::Migration
def self.up
create_table(:admins) do |t|
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
t.integer :sign_in_count, :default => 0
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
t.integer :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
t.string :unlock_token # Only if unlock strategy is :email or :both
t.datetime :locked_at
t.timestamps
end
end
def self.down
drop_table :admins
end
end
end
I have tried a few different things ti try and test this out and figure out what the issue is. Again any help would be appreciated!!
Thanks!!
Update:
Here is my initializer/devise.rb file
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "please-change-me-at-config-initializers-devise#example.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "bf3ea1b40194e484490b93836a07aa303bb7c2bf0acde18ab941011fd664414b1ab520c1e8a805579f74701a4434cbdfa456305b6e432fa4b367abe9c0bed65a"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^#]+#[^#]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
config.unlock_strategy = :email
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :get
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
end
I have tried a few things to get it done, but I have still not been able to fix this.
It looks like you might have added :lockable to the model but the migration didn't create the appropriate fields. Check if you have you have uncommented the lockable fields in devise migration(:failed_attempts, :unlock_token, :locked_at)
I got the same error message by installing the Devise3+Rails4 Example app.
In the example app, users are preconfigured to be :confirmable and :lockable and if you look at the table users you'll see columns such as confirmation_token and confirmed_at as well as failed_attempts and locked_at, while the admin table doesn't have these. The /app/model/user.rb has those two attributes in the call to devise:
devise :database_authenticatable, :registerable, ... :confirmable, :lockable
and /app/model/admin.rb does not. If you add :confirmable and/or :lockable to the Admin model then you'll see this error message. I'm pretty sure the NameError is caused by either a Devise or Rails class implementing method_missing to look for a database table with that name.
I don't know enough about Devise to know the fix off the top of my head but it should be something similar to rake db:migrate so that after you add those attributes in the model, a migration is generated and then executed to add those columns to the admin table.
I've also already configured /config/initializers/devise.rb to enable locking strategies, etc.. as the other answer suggested. In addition, locking and confirming worked for Users prior to the change to the Admin model and continue to work for Users if :confirmable and :lockable are removed from the Admin model.
I am new to Ruby and Rails and having some issues with Devise. I am creating a new Devise installation. Even though, I believe I have properly configured my devise.rb initializer for enabling confirmable; but when I migrate the database the confirmed_at and related fields are not there. I found a ton of posts on how to add it after, but I was wondering if I am doing something wrong or does the
rails generate devise User
command does not generate the Model instances, even if you have then enabled in your devise.rb file before creation?
I am learning so I don't want to add the fields manually if I am configuring my devise.rb file incorrectly from the beginning. Thank you for any help!!!
Attached is my initializer file devise.rb
Devise.setup do |config|
config.mailer_sender = ENV["WEBSITE_FROM_ADDRESS"]
require 'devise/orm/active_record'
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "c2142dc46ff7f7022a10584e2390c4d286af5cb6d3f1bc8c3e59bcbab7a7907608f52dd4159d4ea7fb435c0152fde31814337e5e9700dc1abbff3f2bb49b6c42"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^#]+#[^#]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
end
You need to ensure :confirmable is selected in the User model (i.e. after devise):
app/models/user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:token_authenticatable, :confirmable, :lockable
and the following lines are uncommented in migration file:
db/migrate/devise_create_users.rb
## Confirmable
t.string :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
t.string :unconfirmed_email # Only if using reconfirmable