Devise for user management and authentication.
Below is the details of the Devise Gem.
https://github.com/plataformatec/devise
The main purpose of this tutorial is to implement the devise gem and authenticate a user by user id and email.
Let's come to the implementation.
Step1.First, add devise gem in Gemfile.
gem 'devise', '3.4.1'
Step2.then after installing the gem
bundle install
Step3.Model and View Settings
$ rails generate devise:install
$ rails generate devise MODEL
$ rails generate devise:views
(if you want to change the layout of your views)
Step4.Run the migration.
rake db:migrate
Step5.config/environments/development.rb:
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
Step6.Other configuration settings
in /config/application.rb
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
address: "smtp.gmail.com",
enable_starttls_auto: true,
port: 587,
authentication: :plain,
user_name: ENV["MAIL_USERNAME"],
password: ENV["MAIL_PASSWORD"],
openssl_verify_mode: 'none'
}
for environment settings please check the below article.
http://qiita.com/alokrawat050/items/0d7791b3915579f95791
Step7.Settings, user login by email or user_id
in your /model/user.rb
devise :database_authenticatable, :registerable,:confirmable, :lockable, :timeoutable,:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
here we are using :authentication_keys => [:login], to authenticate user's login.
and also add below code in /model/user.rb.
'# Virtual attribute for authenticating by either user_id or email
This is in addition to a real persisted field like 'user_id'
attr_accessor :login
def login=(login)
@login = login
end
def login
@login || self.user_id || 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(["user_id = :value OR email = :value", { :value => login.downcase }]).first
else
where(conditions.to_h).first
end
end
def send_devise_notification(notification, *args)
devise_mailer.send(notification, self, *args).deliver_later
end
Step8.Add below lline in /config/initializers/devise.rb file
line number 33 → config.authentication_keys = [:login ]
Step9.Changes in views
in /views/devise/sessions/new.html.erb
replace below code:
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
↓
<%= f.label :login %>
<%= f.text_field :login, autofocus: true, class: 'form-control' %>
in /views/devise/registrations/new.html.erb
<%= f.label :user_id %>
<%= f.text_field :user_id, class: 'form-control' %>
Then run your application.
If you have doubts then please feel free to ask.
Enjoy Coding.
Thanks & Best Regards,
Alok Rawat