shou2017.com
JP

rails, add email authentication function

Mon Aug 7, 2017
Sat Aug 10, 2024

Setting up local environment

For now, install gem letter_opener_web, the local environment configuration.

group :development do
  gem 'letter_opener_web'
end

Configuration of routes.rb

# routes.rb
if Rails.env.development?
  mount LetterOpenerWeb::Engine, at: "/letter_opener"
end

Configuration of `config/environments/development.rb

config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_mailer.delivery_method = :letter_opener_web

That’s all. Now all you need to do is access localhost:3000/letter_opener.

Setting up a production environment using heroku

Use sendrid. Plugin installation.

$ heroku addons:create sendgrid:starter

At this point, if you have not registered your credit card in heroku, an error will be displayed.

Configure Sendgrid.

Check SENDGRID_USERNAME and SENDGRID_PASSWORD.

$ heroku config:get SENDGRID_USERNAME
$ heroku config:get SENDGRID_PASSWORD

Configure `config/environments/production.rb

config.action_mailer.default_url_options = { host: 'Domain of my Heroku app' }
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings =
{
 user_name: ENV['SENDGRID_USERNAME'],
 password: ENV['SENDGRID_PASSWORD'],
 domain: "heroku.com",
 address: "smtp.sendgrid.net",
 port: 587,
 authentication: :plain,
 enable_starttls_auto: true
}

環境変数の設定

$ heroku config:set SENDGRID_USERNAME=username
$ heroku config:set SENDGRID_PASSWORD=password

Confirmation that it was done properly.

$ heroku config

config/initializers/devise.rb

Change the value of config.mailer_sender to ’noreply@yourdomain'.

Make sure that a verification email is sent when a new registration is made

Add :confirmable to user.rb.

class User < ActiveRecord::Base  
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable
end

Add columns required for minimum email authentication

$ rails g migration add_confirmable_to_devise

Delete all the resulting files and copy and paste the one below.

class AddConfirmableToDevise < ActiveRecord::Migration
  def up
    add_column :users, :confirmation_token, :string
    add_column :users, :confirmed_at, :datetime
    add_column :users, :confirmation_sent_at, :datetime
    add_column :users, :unconfirmed_email, :string
    add_index :users, :confirmation_token, unique: true
    # User.reset_column_information # Need for some types of updates, but not for update_all.

    execute("UPDATE users SET confirmed_at = NOW()")
  end

  def down
    remove_columns :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
    remove_columns :users, :unconfirmed_email # Only if using reconfirmable
  end
end

Edit the migration file and run rake db:migrate

See Also