Yu-Chieh’s Blog (Y.C. Chang)

Ruby on Rails / Rubygems / FullStack / Git / Mac notes.

Rails Tips: User Authentication Using Devise

  • create a demo project by rails
1
$ rails new topic
  • add gem ‘devise’ to Gemfile then bundle it.
1
2
3
4
# Gemfile
gem 'devise'

$ bundle
  • install into your project, generate user model and views
1
2
3
$ rails generate devise:install
$ rails generate devise User
$ rails generate devise:views
  • configure development.rb for action mailer setting
1
2
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
  • configure application.rb for action mailer setting
1
2
3
4
5
6
7
8
9
10
ActionMailer::Base.smtp_settings = {

        :address        => 'smtp.gmail.com',
        :domain         => 'mail.google.com',
        :port           => 587,
        :user_name      => "your_gmail_account@gmail.com", #ENV['GMAIL_USERNAME'],
        :password       => "weakpass", #ENV['GMAIL_PASSWORD'],
        :authentication => 'login',
        :enable_starttls_auto => true
}
  • generate a scaffold for the topic resource and add registrations controller for overriding devise’s one
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ rails g scaffold topic title
$ rails g controller registrations

# in registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController

  private

  def sign_up_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end

  def account_update_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation, :current_password)
  end
end

# modify route.rb
devise_for :users, controllers: { registrations: "registrations" }
root 'topics#index'

# add the following "before_action" to topics_conftroller.rb for forcing users logging in
before_action :authenticate_user!
done and enjoy it.

Comments