nulltek
nulltek

Reputation: 3337

Devise authenticating with username instead of email

I'm new to Devise and have it working fine by using an email address as the authentication key. However, I have a use case which requires a username instead and I can't seem to get it working.

I've added a string column, "username" to the users table, changed the fields from :email to :username in the sign-in form, and have changed the authentication key in devise.rb to :username yet when I go to sign in I'm met with this prompt: "Please enter an email address".

What am I doing wrong?

**new.html.erb**

  <div><%= f.label :username %><br />
  <%= f.email_field :username %></div>

**User.rb**
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:username]

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username
  # attr_accessible :title, :body
end

**devise.rb**
 config.authentication_keys = [ :username ]

Upvotes: 19

Views: 21974

Answers (4)

Dennis Nedry
Dennis Nedry

Reputation: 4777

i don't know how much has changed since ~2012 but this i what i had to do on Rails 7 in 2022 when changing authentication from email to internal_id.

  1. config.authentication_keys = [:internal_id] (in devise.rb)
  2. add internal_id to user via migration
  3. update the user model to look like this:
devise :database_authenticatable, :rememberable, authentication_keys: [:internal_id]

validates :internal_id, presence: true, uniqueness: { case_sensitive: false }

for 3. it is important to remove the :validatable, :recoverable and :registerable modules from devise.

for more information check:

Upvotes: -1

od-c0d3r
od-c0d3r

Reputation: 66

Adding to rb512 answer

When you set config.authentication_keys to [:username] it's also convenient to set

  • config.case_insensitive_keys = [:username]

  • config.strip_whitespace_keys = [:username]

Upvotes: 1

Kleber S.
Kleber S.

Reputation: 8240

  • First of all, make sure to run the migrations.

bundle exec rake db:migrate

  • Generate the views for Devise, otherwise Devise will use the defaults.

rails generate devise:views

  • Change the Devise/views as you want (replacing email field to username field)

  • Restart the webserver

Hope it helps!

Upvotes: 2

rb512
rb512

Reputation: 6958

In your config/initializers/devise.rb uncomment config.authentication_keys = [ :email] and change it to config.authentication_keys = [ :username ]

Update:
Your form's incorrect.
Change f.email_field to f.text_field

Upvotes: 49

Related Questions