Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ]
like image 900
nulltek Avatar asked Jun 02 '12 23:06

nulltek


People also ask

What is devise authentication?

Devise is a well known solution for authentication in Rails applications. It's full featured (it not only adds authentication but also password recovery, email changing, session timeout, locking, ip tracking, etc.) and can be expanded to add even more (like JWT authentication).

How do you get a password in devise?

Devise initially stores the original password by encrypting it. The encrypted_password (field name in your model) gets stored in the database. Now, when you call User. find_by :email => "[email protected]" the password field is non existing.

What is devise Ruby?

Devise is the cornerstone gem for Ruby on Rails authentication. With Devise, creating a User that can log in and out of your application is so simple because Devise takes care of all the controllers necessary for user creation ( users_controller ) and for user sessions ( users_sessions_controller ).


2 Answers

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

like image 65
rb512 Avatar answered Oct 05 '22 22:10

rb512


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

like image 22
Kleber S. Avatar answered Oct 06 '22 00:10

Kleber S.