deviseでログイン機能を簡単に実装する


はじめに

Railsのgemであるdeviseについて、導入からログイン機能の実装までの手順を紹介します。

deviseとは

ユーザーの新規登録、ログイン、ログアウトなど、認証に必要な機能を追加することができるgemです。

deviseのインストール

Gemfileにdeviseを追加

gem 'devise'

gemをインストールします。

$ bundle install

以下のコマンドで、関連ファイルをインストールします。


$ rails g devise:install

これにより、config/initializers/devise.rb、create config/locales/devise.en.ymlというファイルが作成されます。

deviseの設定

まず、config/environments/development.rbに、以下のURLを追記します。

config/environments/development.rb

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

これは、ユーザーの新規登録などで使われる、認証メールに記載されるURLを設定しています。なので、メールによる認証を行わない場合はスキップして構いません。

また、エラーメッセージを表示させるために、app/views/layouts/application.html.erbに追記します。

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

これを、<%= yield %>の直前に追記します。

ユーザーモデルの作成

認証用のユーザーモデルを作成するには、通常の「rails g model モデル名」ではなく、「rails g devise モデル名」を使います。

$ rails g devise user

作成されたユーザーモデルは、以下のとおりです。

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

この中に記載されているものは、モジュールと呼ばれるもので、それぞれ以下のような機能があります。

・database_authenticatable  DBに保存されるパスワードが正しいかの検証と暗号化
・registerable  サインアップ処理
・recoverable  パスワードのリセット
・rememberable  クッキーにログイン情報を保持
・trackable  サインイン回数・時刻・IPアドレスを保存
・validatable  メールアドレスとパスワードのバリデーション
・confirmable  メール送信による登録確認
・lockable  一定回数ログインに失敗した際のアカウントロック
・timeoutable  一定時間でセッションを削除する
・omniauthable  OmniAuthサポート

デフォルトでは、すべてのモジュールが設定されているわけではないので、必要に応じて追記しましょう。

また、作成されたマイグレーションファイルについても見ていきます。

db/migrate/xxx_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

モジュールを上のapp/models/user.rbで追加した場合、マイグレーションファイル内の対応する部分についても、コメントを外すようにしましょう。

モジュールの編集が終わったら、マイグレーションを実行し、テーブルを作成します。

$ rails db:migrate

この時点で、/users/sign_upにアクセスし、Sign upの画面が表示されれば無事成功です。

あとは、必要に応じて、ビューを編集していきましょう。

ビューの作成

$ rails g devise:views

これにより、モデルに対応するいくつかのビューが作成されます。registrations/new.html.erb(新規登録画面)、sessions/new.html.erb(ログイン画面)、registrations/edit.html.erb(ユーザー編集画面)辺りはよく使うので、必要に応じてレイアウトを編集しましょう。

コントローラの作成

コントローラを編集する場合、以下のコマンドを実行します。

$ rails g devise:controllers users

また、ルーティングの設定もしましょう。例えば、registrations_controller.rb、sessions_controller.rbを使う場合は以下のようにします。

config/routes.rb
devise_for :users, controllers: {
  registrations: 'users/registrations',
  sessions:      'users/sessions',
}

参考サイト