LoginSignup
105
105

More than 5 years have passed since last update.

Rails4 devise導入

Last updated at Posted at 2014-04-16

1. Gemfileに以下を追加

Gemfile
gem 'devise'

2. bundle install を実行

$ bundle install

3. Railsプロジェクトにインストール

$ bundle exec rails generate devise:install

      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:

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

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

===============================================================================

4. 確認メールのアクセス先ホストの設定(サインアップ時に確認メールを出す場合)

確認メールの「Confirm my accounts」のリンクを変更するには、config/environments/development.rbに設定する場合、以下の箇所を修正
※必要に応じてtest.rb,production.rbにも追記

値は環境に応じて変更する

config/environments/development.rb
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }

5. メッセージ表示領域を追加
とりあえずapp/views/layouts/application.html.erbのbodyの一番上に追記
※Twitter bootstrapを使用している場合は不要

app/views/layouts/application.html.erb
<body>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <%= yield %>
</body>

6. Userモデルを作成(DB)

$ rails generate devise user

      invoke  active_record
      create    db/migrate/20150511234956_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users

7. サインアップ時に確認メールを出す(DB)

db/migrate/nnnnnn_devise_create_users.rbのt.confirmableのコメントを外します。

db/migrate/nnnnnn_devise_create_users.rb
      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable

インデックスも一応有効にしておく

db/migrate/nnnnnn_devise_create_users.rb
    add_index :users, :confirmation_token,   unique: true

8. ModelをDBに反映

DBを作成

rake db:create

または

rake db:create:all

で、全ての環境(development, test, production)のDBを作成

してから、マイグレート

$ bundle exec rake db:migrate

9. サインアップ時に確認メールを出す(設定)

9-1. メール送信の設定
config/environments/development.rbの以下の「config.action_mailer.raise_delivery_errors = false」をコメントにする

config/environments/development.rb
  # Don't care if the mailer can't send.
#  config.action_mailer.raise_delivery_errors = false

9-2. SMTPサーバの設定
SMTPサーバの設定config/environments/development.rbに以下を追記
※必要に応じてtest.rb,production.rbにも追記

メールサーバに応じて値は変更する

config/environments/development.rb
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => 'smtp.gmail.com',
    :port => 587,
    :authentication => :plain,
    :user_name => 'xxx@gmail.com',
    :password => '****'
  }

9-3. SES(AWS)でメール認証

config/initializers/devise.rb
config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com"

config.mailer_senderを適切なメールアドレスに変更しましょう。

また、SSLを使用したsmtpsを使用する場合、
設定を変更する必要があります。

下記、設定でできました。

config/environment/development.rb
  config.action_mailer.default_url_options = { :host => '192.168.0.10:3000' }
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    :address => 'email-smtp.us-east-1.amazonaws.com',
    :port => 465,
    :authetication => :login,
    :user_name => 'AKIxxxxxxxxxxxxxxx',
    :domain => "sample.com",
    :password => 'Ajxxxxxxxxxxxxxxx',
    :ssl => true,
    :tls => true,
    :enable_starttls_auto => true,
  }

※AWSのSESを使用して、登録時のメール認証を行う場合、SESに登録されているメールアドレスから送信する必要があります。

9-4. Userモデルの設定

サインアップ時に確認メールを送信するかどうかの設定はdeviseのモデル app/models/user.rbのdeviseメソッドの引数として指定する。
confirmableを追加

app/models/user.rb
  devise :database_authenticatable, :registerable,:confirmable,
         :recoverable, :rememberable, :trackable, :validatable

※変更前には下記のようなファイルが作成されていると思います。

app/models/user.rb
clarss User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

10. 認証チェック追加方法
必要に応じてControllerに認証チェックを追加

app/controllers/xxxxx.rb
before_filter :authenticate_user!

11. viewのカスタマイズ

生成されたそれぞれのビューを編集すると、デフォルトのビューの変わりに表示されるようになる。
ログインフォームを編集する場合は、以下のファイルを編集する。
app/views/devise/sessions/new.html.erb

$ rails generate devise:views
 devise:views
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb
      create    app/views/devise/shared
      create    app/views/devise/shared/_links.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb

12. その他メソッドについて

認可を必要とするコントローラーの before_action で以下のように指定。ユーザーのモデル名が User の場合は以下。

app/controllers/xxxxxx.rb
before_action :authenticate_user!

ユーザーがサインインしているかどうかを検証するメソッド。

app/controllers/xxxxxx.rb
user_signed_in?

現在サインインしているユーザーを取得。

app/controllers/xxxxxx.rb
current_user

ユーザーのセッション情報にアクセス。

app/controllers/xxxxxx.rb
user_session

※その他メソッドはコントローラで使用する場合が多いがviewなどでも使用できる

105
105
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
105
105