Thursday, 4 October 2018

Login with username

Please visit site:

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

Create a migration:

rails generate migration add_username_to_users username:string:uniq

Run the migration:

rake db:migrate
User.rb:

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable, authentication_keys: [:login]

attr_writer :login

validates :username, presence: :true, uniqueness: { case_sensitive: false }
  validate :validate_username

def login
    @login || self.username || self.email
  end
  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    elsif conditions.has_key?(:username) || conditions.has_key?(:email)
      where(conditions.to_h).first
    end
  end
  def validate_username
    if User.where(email: username).exists?
      errors.add(:username, :invalid)
    end
  end
=========================================================

Modify config/initializers/devise.rb to have:
config.authentication_keys = [ :login ]

Application.rb

config.exceptions_app = self.routes

Modify the views

sessions/new.html.erb:
  -  <p><%= f.label :email %><br />
  -  <%= f.email_field :email %></p>
  +  <p><%= f.label :login %><br />
  +  <%= f.text_field :login %></p>
Use :login and not :username in the sessions/new.html.erb
registrations/new.html.erb:
  +  <p><%= f.label :username %><br />
  +  <%= f.text_field :username %></p>
     <p><%= f.label :email %><br />
     <%= f.email_field :email %></p>
registrations/edit.html.erb:
  +  <p><%= f.label :username %><br />
  +  <%= f.text_field :username %></p>
     <p><%= f.label :email %><br />
     <%= f.email_field :email %></p>

Configure Devise to use username as reset password or confirmation keys

Simply modify config/initializers/devise.rb to have:
config.reset_password_keys = [ :username ]
config.confirmation_keys = [ :username ]

















No comments:

Post a Comment